DS18B20.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. logger(V_HAL, "Checking 1-Wire Bus for sensors..\n");
  29. DS18B20_readRom();
  30. deviceID = double (rom[1]);// | ROM[5] << 8 | ROM[5] << 16 | ROM[5] << 24 | ROM[5] << 32 | ROM[5] << 40);
  31. if(rom[7] == 0x28){
  32. logger(V_HAL, "Found temperatur sensor on 1-Wire Bus\n");
  33. logger(V_HAL, "Device ID: %12X\n", deviceID);
  34. }
  35. }
  36. void DS18B20_readRom(void){
  37. OW_writeByte(READ_ROM);
  38. int i;
  39. for(i = 7; i >= 0; i--){
  40. rom[i] = OW_readByte();
  41. }
  42. }
  43. /**
  44. * Reads the Temperatur of the DS18B20 Sensor
  45. * It rounds the value read from the Sensor rounded to the next integer
  46. */
  47. int8_t DS18B20_readTemp (void){
  48. OW_writeByte(SKIP_ROM);
  49. OW_writeByte(CONVERT_T);
  50. while(!OW_readBit()){
  51. //wait to finish conversion
  52. //TODO don't wait forever
  53. }
  54. OW_writeByte(READ_SCRATCH);
  55. uint8_t scratchPad[9];
  56. uint8_t i;
  57. int8_t temp;
  58. for(i = 0; i < 9; i++){
  59. scratchPad[i] = OW_readByte();
  60. }
  61. //Information about temperatur is stored in byte[0] and byte[1]
  62. temp = scratchPad[0] >> 4;
  63. temp |= (scratchPad[1] << 4) & 0xF0;
  64. return temp;
  65. //todo return a float value and do proper rounding
  66. }