DS18B20 Temperature Sensor with Arduino

Arduino Experiment: Read Temperature with DS18B20 Sensor

Difficulty Level: Intermediate

Learn how to connect and read temperature data from the DS18B20 temperature sensor using an Arduino. This project uses the serial monitor to display temperature readings in real time.

1. Required Components

2. DS18B20 Pinout

Follow these connections to interface the DS18B20 sensor with your Arduino:

Note: Place a 4.7kΩ resistor between the DQ and VDD pins for proper operation.

3. Code Explanation

The code utilizes the OneWire and DallasTemperature libraries to manage communication with the DS18B20 sensor. Here's an overview of the main functions:

Installing Required Libraries

Before uploading the code, install the required libraries:

  1. In the Arduino IDE, navigate to Sketch > Include Library > Manage Libraries....
  2. Search for OneWire and click "Install."
  3. Search for DallasTemperature and click "Install."

4. Arduino Code

Use the following code to read the temperature data from the DS18B20 sensor:


// Include necessary libraries
#include 
#include 

// Pin to which the DS18B20 data line is connected
#define ONE_WIRE_BUS 2

// Initialize OneWire instance and pass it to DallasTemperature library
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup() {
  // Start serial communication
  Serial.begin(9600);
  
  // Initialize the temperature sensor library
  sensors.begin();
}

void loop() {
  // Request temperature data from the sensor
  sensors.requestTemperatures();
  
  // Get temperature in Celsius
  float temperatureC = sensors.getTempCByIndex(0);

  // Print the temperature to the serial monitor
  Serial.print("Temperature: ");
  Serial.print(temperatureC);
  Serial.println(" °C");

  // Wait for 1 second before the next reading
  delay(1000);
}
            

5. Upload and Test

Follow these steps to upload the code and test your setup:

  1. Connect your Arduino to your PC using a USB cable.
  2. Open the Arduino IDE and paste the code above into a new sketch.
  3. Install the required libraries if you haven’t already.
  4. Select the correct board and port under Tools in the IDE.
  5. Click the upload button to program your Arduino.
  6. Open the Serial Monitor (set baud rate to 9600) to see real-time temperature readings.

6. Additional Tips

7. Conclusion

This experiment showed how to interface the DS18B20 sensor with an Arduino to measure and display temperature data. This simple setup is highly versatile and can be integrated into larger projects such as weather stations, home automation systems, or industrial temperature monitoring.