Advertisement
Guest User

TS18B20-Temperature-Sensor

a guest
Feb 11th, 2016
306
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. OneWire ds(10); // on pin 10
  2.  
  3. void setup(void) {
  4. Serial.begin(9600);
  5. }
  6.  
  7. void loop(void) {
  8. byte i;
  9. byte present = 0;
  10. byte type_s;
  11. byte data[12];
  12. byte addr[8];
  13. float celsius, fahrenheit;
  14.  
  15. if ( !ds.search(addr)) {
  16. Serial.println("No more addresses.");
  17. Serial.println();
  18. ds.reset_search();
  19. delay(250);
  20. return;
  21. }
  22.  
  23. Serial.print("ROM =");
  24. for( i = 0; i < 8; i++) {
  25. Serial.write(' ');
  26. Serial.print(addr[i], HEX);
  27. }
  28.  
  29. if (OneWire::crc8(addr, 7) != addr[7]) {
  30. Serial.println("CRC is not valid!");
  31. return;
  32. }
  33. Serial.println();
  34.  
  35. // the first ROM byte indicates which chip
  36.  
  37. if (addr[0]==0x28){
  38. Serial.println(" Chip = DS18B20");
  39. type_s = 0;
  40. }else{
  41. Serial.println("Device is not a DS18x20 family device.");
  42. return;
  43. }
  44.  
  45.  
  46. ds.reset();
  47. ds.select(addr);
  48. ds.write(0x44,1); // start conversion, with parasite power on at the end
  49.  
  50. delay(1000); // maybe 750ms is enough, maybe not
  51. // we might do a ds.depower() here, but the reset will take care of it.
  52.  
  53. present = ds.reset();
  54. ds.select(addr);
  55. ds.write(0xBE); // Read Scratchpad
  56.  
  57. Serial.print(" Data = ");
  58. Serial.print(present,HEX);
  59. Serial.print("");
  60. for ( i = 0; i < 9; i++) { // we need 9 bytes
  61. data[i] = ds.read();
  62. Serial.print(data[i], HEX);
  63. Serial.print("");
  64. }
  65. Serial.print(" CRC=");
  66. Serial.print(OneWire::crc8(data, 8), HEX);
  67. Serial.println();
  68.  
  69. // convert the data to actual temperature
  70.  
  71. unsigned int raw = (data[1] << 8) | data[0];
  72.  
  73. byte cfg = (data[4] & 0x60);
  74. if (cfg == 0x00) raw = raw << 3; // 9 bit resolution, 93.75 ms
  75. else if (cfg == 0x20) raw = raw << 2; // 10 bit res, 187.5 ms
  76. else if (cfg == 0x40) raw = raw << 1; // 11 bit res, 375 ms
  77. // default is 12 bit resolution, 750 ms conversion time
  78.  
  79. celsius = (float)raw / 16.0;
  80. fahrenheit = celsius * 1.8 + 32.0;
  81. Serial.print(" Temperature = ");
  82. Serial.print(celsius);
  83. Serial.print(" Celsius, ");
  84. Serial.print(fahrenheit);
  85. Serial.println(" Fahrenheit");
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement