ds18b20.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. void gettemp(void){
  18. unsigned char i, crc=0, tmp;
  19. static unsigned char error_cnt;
  20. unsigned char temp_ok_out = 0;
  21. float temp;
  22. if(System.timers.owire) return;
  23. _delay_ms(1);
  24. if(_1WireInit() != 1){
  25. return;
  26. }
  27. _1WireWriteByte(0xcc);
  28. _1WireWriteByte(0xbe);
  29. for(i=0;i<9;i++){
  30. tmp = _1WireReadByte();
  31. t.owbuffer[i] = tmp;
  32. crc = _crc_ibutton_update(crc, tmp);
  33. }
  34. if(!crc){
  35. if(t.owbuffer[0] != 0x50 || t.owbuffer[1] != 0x05 || t.owbuffer[5] != 0xff || t.owbuffer[7] != 0x10){
  36. temp = (float)t.t*0.0625;
  37. System.temperature = temp;
  38. temp_ok_out = 1;
  39. }
  40. }
  41. if(!temp_ok_out){
  42. if(error_cnt > MAX_ERRORS){
  43. System.temperature_ok = 0;
  44. } else {
  45. error_cnt++;
  46. }
  47. } else {
  48. error_cnt = 0;
  49. System.temperature_ok = 1;
  50. }
  51. _1WireInit();
  52. _1WireWriteByte(0xcc);
  53. _1WireWriteByte(0x44);
  54. atomic_set_uint(&System.timers.owire, ms(4000));
  55. }