Advertisement
microrobotics

18B20 Arduino Code

Mar 30th, 2023
12,620
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //Here's an example code in Arduino that reads the temperature from an 18B20 sensor connected to an Arduino board:
  2. //Note: This code assumes that the 18B20 sensor is connected to pin 2 of the Arduino board. If you're using a different pin, you'll //need to modify the ONE_WIRE_BUS definition accordingly.
  3.  
  4. #include <OneWire.h>
  5.  
  6. // Data wire is connected to pin 2
  7. #define ONE_WIRE_BUS 2
  8.  
  9. OneWire oneWire(ONE_WIRE_BUS);
  10.  
  11. void setup() {
  12.   Serial.begin(9600);
  13. }
  14.  
  15. void loop() {
  16.   byte i;
  17.   byte present = 0;
  18.   byte type_s;
  19.   byte data[12];
  20.   byte addr[8];
  21.  
  22.   // start reading from the 18B20 sensor
  23.   if (!oneWire.search(addr)) {
  24.     Serial.println("No more addresses.");
  25.     oneWire.reset_search();
  26.     delay(250);
  27.     return;
  28.   }
  29.  
  30.   // check the CRC of the address
  31.   if (OneWire::crc8(addr, 7) != addr[7]) {
  32.     Serial.println("CRC is not valid!");
  33.     return;
  34.   }
  35.  
  36.   // the first ROM byte indicates which chip
  37.   switch (addr[0]) {
  38.     case 0x10:
  39.       type_s = 1;
  40.       break;
  41.     case 0x28:
  42.       type_s = 0;
  43.       break;
  44.     case 0x22:
  45.       type_s = 0;
  46.       break;
  47.     default:
  48.       Serial.println("Device is not recognized!");
  49.       return;
  50.   }
  51.  
  52.   // start conversion
  53.   oneWire.reset();
  54.   oneWire.select(addr);
  55.   oneWire.write(0x44, 1);
  56.  
  57.   // wait for conversion to complete
  58.   delay(1000);
  59.  
  60.   // read scratchpad
  61.   present = oneWire.reset();
  62.   oneWire.select(addr);
  63.   oneWire.write(0xBE);
  64.  
  65.   // read data
  66.   for (i = 0; i < 9; i++) {
  67.     data[i] = oneWire.read();
  68.   }
  69.  
  70.   // convert temperature data
  71.   int16_t raw = (data[1] << 8) | data[0];
  72.   float celsius = (float)raw / 16.0;
  73.  
  74.   // print temperature
  75.   Serial.print("Temperature: ");
  76.   Serial.print(celsius);
  77.   Serial.println(" °C");
  78.  
  79.   // delay before reading from the sensor again
  80.   delay(1000);
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement