ds18b20.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include <string.h>
  2. #include <util/crc16.h>
  3. #include <util/delay.h>
  4. #include "main.h"
  5. #include "ds18b20.h"
  6. #include "1wire.h"
  7. union {
  8. signed int t;
  9. unsigned char owbuffer[9];
  10. } t;
  11. #define MAX_ERRORS 5
  12. unsigned char rom_num;
  13. unsigned char rom_tab[MAX_SENSOR_NUM][8];
  14. unsigned char temp_ok;
  15. signed int temps[MAX_SENSOR_NUM];
  16. unsigned char find_1wire(void){
  17. unsigned char rom[8];
  18. unsigned char i=0, rv=0, j;
  19. unsigned char crc = 0;
  20. do {
  21. rv = _1WireSearch(rv, rom);
  22. memcpy(rom_tab[i], rom, 8);
  23. for(j=0;j<8;j++){
  24. crc = _crc_ibutton_update(crc, rom[j]);
  25. }
  26. if(crc) return 1;
  27. i++;
  28. } while(rv && i<MAX_SENSOR_NUM);
  29. rom_num = i;
  30. return 0;
  31. }
  32. void gettemp(void){
  33. unsigned char i, j, crc=0, tmp;
  34. static unsigned char error_cnt[MAX_SENSOR_NUM];
  35. signed int temp;
  36. unsigned char temp_ok_out = 0;
  37. if(timers.owire) return;
  38. _1WirePoweroff();
  39. _delay_ms(1);
  40. for(j=0; j<rom_num; j++){
  41. if(_1WireInit() != 1){
  42. rom_num = 0;
  43. break;
  44. }
  45. _1WireWriteByte(0x55);
  46. _1WireSendRom(rom_tab[j]);
  47. _1WireWriteByte(0xbe);
  48. for(i=0;i<9;i++){
  49. tmp = _1WireReadByte();
  50. t.owbuffer[i] = tmp;
  51. crc = _crc_ibutton_update(crc, tmp);
  52. }
  53. if(!crc){
  54. if(t.owbuffer[0] == 0x50 && t.owbuffer[1] == 0x05 && t.owbuffer[5] == 0xff && t.owbuffer[7] == 0x10) continue;
  55. temp = t.t;
  56. temp *= (int)(0.625*16);
  57. temp >>= 4;
  58. if(t.owbuffer[2] <= MAX_SENSOR_NUM){
  59. temps[t.owbuffer[2]] = temp;
  60. temp_ok_out |= 1<<t.owbuffer[2];
  61. }
  62. }
  63. }
  64. for(i=0; i<MAX_SENSOR_NUM; i++){
  65. if(!(temp_ok_out & (1<<i))){
  66. if(error_cnt[i] > MAX_ERRORS){
  67. temp_ok &= ~(1<<i);
  68. } else {
  69. error_cnt[i]++;
  70. }
  71. } else {
  72. error_cnt[i] = 0;
  73. temp_ok |= 1<<i;
  74. }
  75. }
  76. find_1wire();
  77. _1WireInit();
  78. _1WireWriteByte(0xcc);
  79. _1WireWriteBytePR(0x44);
  80. atomic_set_uint(&timers.owire, ms(4000));
  81. }