ds18b20.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. /* No presence pulse (bus short, or no sensor at all): skip straight to
  25. * the error accounting below instead of returning here - an early
  26. * return would skip re-arming System.timers.owire at the end of this
  27. * function, so with no sensor ever connected, this whole function would
  28. * run on every single main loop pass (never gated by the timer again)
  29. * instead of the intended once-per-4s poll. */
  30. if(_1WireInit() == 1){
  31. _1WireWriteByte(0xcc);
  32. _1WireWriteByte(0xbe);
  33. for(i=0;i<9;i++){
  34. tmp = _1WireReadByte();
  35. t.owbuffer[i] = tmp;
  36. crc = _crc_ibutton_update(crc, tmp);
  37. }
  38. if(!crc){
  39. /* Reject the power-on-reset scratchpad default (85.0C) still in
  40. * place if a conversion never actually completed. */
  41. if(t.owbuffer[0] != 0x50 || t.owbuffer[1] != 0x05 || t.owbuffer[5] != 0xff || t.owbuffer[7] != 0x10){
  42. temp = (float)t.t*0.0625;
  43. System.temperature = temp;
  44. temp_ok_out = 1;
  45. }
  46. }
  47. }
  48. if(!temp_ok_out){
  49. if(error_cnt > MAX_ERRORS){
  50. System.temperature_ok = 0;
  51. } else {
  52. error_cnt++;
  53. }
  54. } else {
  55. error_cnt = 0;
  56. System.temperature_ok = 1;
  57. }
  58. if(_1WireInit() == 1){
  59. _1WireWriteByte(0xcc);
  60. _1WireWriteBytePR(0x44);
  61. }
  62. atomic_set_uint(&System.timers.owire, ms(4000));
  63. }