DS18B20.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * DS18B20.cpp
  3. *
  4. * Created on: Feb 28, 2018
  5. * Author: sebastian
  6. */
  7. #define READ_SCRATCH 0xBE
  8. #define WRITE_SCRATCH 0x4E
  9. #define READ_ROM 0x33
  10. #define SKIP_ROM 0xCC
  11. #define CONVERT_T 0x44
  12. #include "DS18B20.h"
  13. /*
  14. * | -- 8 BIT CRC -- | -- 48 BIT SERIAL NUMBER -- | -- 8 BIT FAMILY CODE (28h) -- |
  15. */
  16. uint8_t ROM[8] = {0,0,0,0,0,0,0,0};
  17. double deviceID;
  18. /**
  19. * initialize the Temperatur Sensor
  20. * This lib is written for only ONE device on the 1-Wire Bus
  21. */
  22. void DS18B20_init(void){
  23. OneWire_init();
  24. if(OW_reset()){
  25. logger_error("Unable to reset 1-Wire Bus, no Device present %s\n", strerror(errno));
  26. return;
  27. }
  28. DS18B20_readRom();
  29. deviceID = double (ROM[1]);// | ROM[5] << 8 | ROM[5] << 16 | ROM[5] << 24 | ROM[5] << 32 | ROM[5] << 40);
  30. if(ROM[7] == 0x28){
  31. logger(V_HAL, "Found Temperatur Sensor on 1-Wire Bus\n");
  32. logger(V_HAL, "Device ID: %12X", deviceID);
  33. }
  34. }
  35. void DS18B20_readRom(void){
  36. OW_writeByte(READ_ROM);
  37. uint8_t i;
  38. for(i = 8; i >= 0; i--){
  39. ROM[i] = OW_readByte();
  40. }
  41. }
  42. /**
  43. * Reads the Temperatur of the DS18B20 Sensor
  44. * It rounds the value read from the Sensor rounded to the next integer
  45. */
  46. int8_t DS18B20_readTemp (void){
  47. OW_writeByte(SKIP_ROM);
  48. OW_writeByte(CONVERT_T);
  49. while(!OW_readBit()){
  50. //wait to finish conversion
  51. //TODO don't wait forever
  52. }
  53. OW_writeByte(READ_SCRATCH);
  54. uint8_t scratchPad[9];
  55. uint8_t i;
  56. int8_t temp;
  57. for(i = 0; i < 9; i++){
  58. scratchPad[i] = OW_readByte();
  59. }
  60. //Information about temperatur is stored in byte[0] and byte[1]
  61. temp = scratchPad[0] >> 4;
  62. temp |= (scratchPad[1] << 4) & 0xF0;
  63. return temp;
  64. //todo return a float value and do proper rounding
  65. }