1
0

ds18b20.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * ds18b20.c - single sensor support
  3. * k4be 2019
  4. * License: BSD
  5. */
  6. #include <string.h>
  7. #include <util/crc16.h>
  8. #include <util/delay.h>
  9. #include "main.h"
  10. #include "ds18b20.h"
  11. #include "1wire.h"
  12. union {
  13. signed int t;
  14. unsigned char owbuffer[9];
  15. } t;
  16. #define MAX_ERRORS 5
  17. unsigned char temp_ok;
  18. signed int ds18b20_temp;
  19. void gettemp(void){
  20. unsigned char i, crc=0, tmp;
  21. static unsigned char error_cnt;
  22. unsigned char temp_ok_out = 0;
  23. signed int temp;
  24. if(System.timers.owire) return;
  25. _delay_ms(1);
  26. if(_1WireInit() != 1){
  27. return;
  28. }
  29. _1WireWriteByte(0xcc);
  30. _1WireWriteByte(0xbe);
  31. for(i=0;i<9;i++){
  32. tmp = _1WireReadByte();
  33. t.owbuffer[i] = tmp;
  34. crc = _crc_ibutton_update(crc, tmp);
  35. }
  36. if(!crc){
  37. if(t.owbuffer[0] != 0x50 || t.owbuffer[1] != 0x05 || t.owbuffer[5] != 0xff || t.owbuffer[7] != 0x10){
  38. temp = t.t;
  39. temp *= (int)(0.625*16);
  40. temp >>= 4;
  41. ds18b20_temp = temp;
  42. temp_ok_out = 1;
  43. }
  44. }
  45. if(!temp_ok_out){
  46. if(error_cnt > MAX_ERRORS){
  47. temp_ok = 0;
  48. } else {
  49. error_cnt++;
  50. }
  51. } else {
  52. error_cnt = 0;
  53. temp_ok = 1;
  54. }
  55. _1WireInit();
  56. _1WireWriteByte(0xcc);
  57. _1WireWriteByte(0x44);
  58. atomic_set_uint(&System.timers.owire, ms(4000));
  59. }