ds18b20.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * ds18b20.c
  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. float hs_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. if(System.timers.owire) return;
  24. _delay_ms(1);
  25. if(_1WireInit() != 1){
  26. return;
  27. }
  28. _1WireWriteByte(0xcc);
  29. _1WireWriteByte(0xbe);
  30. for(i=0;i<9;i++){
  31. tmp = _1WireReadByte();
  32. t.owbuffer[i] = tmp;
  33. crc = _crc_ibutton_update(crc, tmp);
  34. }
  35. if(!crc){
  36. if(t.owbuffer[0] != 0x50 || t.owbuffer[1] != 0x05 || t.owbuffer[5] != 0xff || t.owbuffer[7] != 0x10){
  37. hs_temp = (float)t.t * 0.0625;
  38. temp_ok_out = 1;
  39. }
  40. }
  41. if(!temp_ok_out){
  42. if(error_cnt > MAX_ERRORS){
  43. temp_ok = 0;
  44. } else {
  45. error_cnt++;
  46. }
  47. } else {
  48. error_cnt = 0;
  49. temp_ok = 1;
  50. }
  51. _1WireInit();
  52. _1WireWriteByte(0xcc);
  53. _1WireWriteByte(0x44);
  54. atomic_set_uint(&System.timers.owire, ms(4000));
  55. }