Introduction
This experiment uses the DS18B20 temperature sensor to measure the ambient temperature and display it on the serial monitor. The DS18B20 is a digital thermometer with a wide temperature range and high accuracy.
Components Needed
- Arduino (e.g., Uno, Nano)
- DS18B20 Temperature Sensor
- 4.7kΩ Resistor
- Jumper wires
Circuit Setup
- Connect the VCC pin of the DS18B20 to the 5V pin on the Arduino.
- Connect the GND pin to GND on the Arduino.
- Connect the DATA pin to pin 2 on the Arduino.
- Place a 4.7kΩ resistor between the DATA and VCC pins to act as a pull-up resistor.
Ensure that the sensor is correctly connected and powered before starting the experiment.
Code for Digital Thermometer
Upload the following code to your Arduino to read temperature data:
#include
#include
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
void setup() {
Serial.begin(9600);
sensors.begin();
}
void loop() {
sensors.requestTemperatures();
Serial.print("Temperature: ");
Serial.print(sensors.getTempCByIndex(0));
Serial.println(" C");
delay(1000);
}
Explanation
This code reads the temperature data from the DS18B20 sensor and displays it on the serial monitor. Here's a breakdown of the code:
DallasTemperature sensors(&oneWire)
: Initializes the DS18B20 sensor on the specified pin.sensors.requestTemperatures()
: Requests the current temperature reading from the sensor.sensors.getTempCByIndex(0)
: Retrieves the temperature in Celsius for the first sensor (in case you have multiple sensors).
Troubleshooting
- If no temperature readings appear, check the wiring, especially the pull-up resistor between DATA and VCC.
- If the readings are inaccurate, ensure the sensor is not exposed to extreme environmental conditions that exceed its range.
- Ensure that the OneWire and DallasTemperature libraries are installed in your Arduino IDE.