DS18B20.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 Temperature 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\n");
  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 temperature 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. * Transmits a command to the sensor
  45. * @param cmd Command byte
  46. */
  47. void DS18B20_cmd(uint8_t cmd) {
  48. if(OW_reset()){
  49. logger_error("Unable to reset 1-Wire Bus, no device present\n");
  50. }
  51. OW_writeByte(SKIP_ROM);
  52. OW_writeByte(cmd);
  53. }
  54. /**
  55. * Reads the Temperature of the DS18B20 Sensor
  56. * It rounds the value read from the Sensor rounded to the next integer
  57. */
  58. int8_t DS18B20_readTemp (void){
  59. DS18B20_cmd(CONVERT_T);
  60. while(!OW_readBit()){
  61. //wait to finish conversion
  62. //TODO don't wait forever
  63. }
  64. uint8_t scratchPad[9];
  65. uint8_t i;
  66. int8_t temp;
  67. DS18B20_cmd(READ_SCRATCH);
  68. for(i = 0; i < 9; i++){
  69. scratchPad[i] = OW_readByte();
  70. }
  71. //Information about temperature is stored in byte[0] and byte[1]
  72. temp = scratchPad[0] >> 4;
  73. temp |= (scratchPad[1] << 4) & 0xF0;
  74. return temp;
  75. //todo return a float value and do proper rounding
  76. }