1-wire Temperature Sensor (DS18B20)
Intro
This example shows you how to connect a 1-wire temperature sensor to the NEXTuino device and read the temperature or address of the sensor on the bus.
DS18B20 is a 1-Wire digital temperature sensor from Maxim IC. Reports degrees in Celsius or Fahrenheit with 9 to 12-bit precision, from –55°C to +125°C (±0.5°C). Each sensor has a unique 64-Bit Serial number — allows for a huge number of sensors to be used on one data bus.
IMPORTANT: Please select the proper target board in Tools > Board > NEXTuino RISE/MAXI/MEGA before uploading to your NEXTuino.
Hardware Required
- NEXTuino RISE/MAXI/MEGA
- 12/24V DC Power supply
- DS18B20 – 1-wire temperature sensor
- 4.7 kΩ resistor
Circuit
Connect the sensor’s data pin to any digital, relay output (5V pin), or communication pin (e.g., the SDA pin). A 4.7kΩ pull-up resistor is required between the data line and VCC.
Note: Pin header is working on 5V TTL levels. Voltage levels over 5.5V can damage the NEXTuino permanently.
Code
Install the OneWire library: Sketch > Include Library > Manage Libraries (OneWire 2.3.3 or later).
Open File > Examples > OneWire > DS18x20_Temperature and change the data pin in line OneWire ds(20); to match your wiring.
#include <OneWire.h>
OneWire ds(20); // on pin 20 (a 4.7K resistor is necessary)
void setup(void) {
Serial.begin(9600);
}
void loop(void) {
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
float celsius, fahrenheit;
if (!ds.search(addr)) {
Serial.println("No more addresses.");
Serial.println();
ds.reset_search();
delay(250);
return;
}
Serial.print("ROM =");
for (i = 0; i < 8; i++) {
Serial.write(' ');
Serial.print(addr[i], HEX);
}
if (OneWire::crc8(addr, 7) != addr[7]) {
Serial.println("CRC is not valid!");
return;
}
Serial.println();
switch (addr[0]) {
case 0x10:
Serial.println(" Chip = DS18S20");
type_s = 1;
break;
case 0x28:
Serial.println(" Chip = DS18B20");
type_s = 0;
break;
case 0x22:
Serial.println(" Chip = DS1822");
type_s = 0;
break;
default:
Serial.println("Device is not a DS18x20 family device.");
return;
}
ds.reset();
ds.select(addr);
ds.write(0x44, 1); // start conversion
delay(1000);
present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad
Serial.print(" Data = ");
Serial.print(present, HEX);
Serial.print(" ");
for (i = 0; i < 9; i++) {
data[i] = ds.read();
Serial.print(data[i], HEX);
Serial.print(" ");
}
Serial.print(" CRC=");
Serial.print(OneWire::crc8(data, 8), HEX);
Serial.println();
int16_t raw = (data[1] << 8) | data[0];
if (type_s) {
raw = raw << 3;
if (data[7] == 0x10) {
raw = (raw & 0xFFF0) + 12 - data[6];
}
} else {
byte cfg = (data[4] & 0x60);
if (cfg == 0x00) raw = raw & ~7;
else if (cfg == 0x20) raw = raw & ~3;
else if (cfg == 0x40) raw = raw & ~1;
}
celsius = (float)raw / 16.0;
fahrenheit = celsius * 1.8 + 32.0;
Serial.print(" Temperature = ");
Serial.print(celsius);
Serial.print(" Celsius, ");
Serial.print(fahrenheit);
Serial.println(" Fahrenheit");
}