The DS18B20 is a digital temperature sensor that provides 9-bit to 12-bit Celsius temperature measurements. The sensor communicates over a 1-Wire bus that by definition requires only one data line (and ground) for communication with a central microprocessor. It has an alarm function with nonvolatile user-programmable upper and lower trigger points. The DS18B20 is widely used in a variety of applications, including HVAC environmental controls, temperature monitoring systems inside buildings, equipment, or machinery, and process monitoring and control systems.
Pin Number | Name | Description |
---|---|---|
1 | GND | Ground |
2 | DQ | Data Line |
3 | VDD | Power Supply |
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
void setup(void)
{
// Start serial communication for debugging
Serial.begin(9600);
// Start up the library
sensors.begin();
}
void loop(void)
{
// Call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
sensors.requestTemperatures();
// Fetch the temperature in degrees Celsius for device index 0
float tempC = sensors.getTempCByIndex(0);
// Check if reading was successful
if(tempC != DEVICE_DISCONNECTED_C)
{
Serial.print("Temperature: ");
Serial.print(tempC);
Serial.println("°C");
}
else
{
Serial.println("Error: Could not read temperature data");
}
delay(1000);
}
Q: Can I connect multiple DS18B20 sensors to the same data line?
A: Yes, the DS18B20 supports multi-drop capability, allowing multiple sensors to be connected on the same 1-Wire bus.
Q: How do I set the resolution of the temperature measurements?
A: The resolution can be set programmatically using the DallasTemperature library functions. Refer to the library documentation for specific instructions.
Q: What is the purpose of the unique 64-bit serial code?
A: The unique serial code allows for the identification of each sensor on a shared 1-Wire bus, which is essential for addressing specific sensors in a multi-sensor setup.
Q: How long can the cable be between the sensor and the microcontroller?
A: The maximum cable length depends on the quality of the cable and the pull-up resistor value. For longer cables, a lower value resistor may be needed to maintain signal integrity. Keep the cable as short as practical to ensure reliable communication.