Featured image of post Reading Temperature from DS18B20 Sensor Using Raspberry Pi and Python

Reading Temperature from DS18B20 Sensor Using Raspberry Pi and Python

In Raspberry Pi projects, we often need to use sensors to gather environmental data. The DS18B20 is a commonly used digital temperature sensor that can...

In Raspberry Pi projects, it’s common to use sensors to collect environmental data. The DS18B20 is a widely used digital temperature sensor that can read temperature values via the GPIO interface on the Raspberry Pi. This article will explain how to connect the DS18B20 sensor and write Python code to continuously read temperature values.

First, let’s understand the basic principle behind the DS18B20 sensor. The DS18B20 is a digital temperature sensor known for its high precision and relatively wide measurement range. It communicates with the Raspberry Pi using a one-wire interface, providing power and data transmission through the GPIO pins.

1. Connections:

The steps to connect the DS18B20 sensor to the Raspberry Pi are as follows:

  1. Connect the VCC pin of the DS18B20 sensor to the 3.3V power pin on the Raspberry Pi.
  2. Connect the GND pin of the DS18B20 sensor to a ground (GND) pin on the Raspberry Pi.
  3. Connect the data pin of the DS18B20 sensor to a GPIO pin on the Raspberry Pi. We recommend using GPIO4.

Here’s a diagram of the connection:

1
2
3
4
5
6
7
          DS18B20 Module
           +-------+
           |       |
    3.3V-->| VCC   |
           |       |     GPIO4 <--------| DATA |
           |       |     Ground------->| GND |
           +-------+

2. Configuration and Manual Reading:

The basic steps to read the temperature using the DS18B20 module are as follows:

  1. Enable DS18B20 support on the Raspberry Pi: Open a terminal and type the following command to ensure that the “w1-gpio” and “w1-therm” kernel modules are enabled:

    1
    
    sudo nano /boot/config.txt
    

    Add the following two lines at the end of the file:

    1
    2
    
    dtoverlay=w1-gpio
    dtoverlay=w1-therm
    

    Save and exit the file, then reboot the Raspberry Pi for the changes to take effect.

  2. Connect the DS18B20 module: Ensure that the DS18B20 module is connected to the GPIO interface on the Raspberry Pi; please refer to the module documentation or resources for specific connection instructions.

  3. To read the temperature value, open a terminal and input the following commands to access the DS18B20 module’s temperature value:

    1
    2
    
    cd /sys/bus/w1/devices/
    ls
    

    A directory name starting with “28-” should appear, which serves as the unique identifier for the DS18B20 module. Replace “<device_id>” in the following command with that name to read the temperature value:

    1
    
    cat /sys/bus/w1/devices/<device_id>/w1_slave
    

    This command will return a text string containing the temperature value, marked by “t=”. Divide the value following “t=” by 1000 to obtain the temperature in degrees Celsius.

    Note that the DS18B20 module requires a bit of time to measure the temperature accurately, so you should wait a moment (e.g., 1 second) before reading the temperature to ensure the measurement is complete. Additionally, check the electrical connections between the Raspberry Pi and the DS18B20 module to ensure accurate temperature readings.

3. Python Loop for Continuous Reading:

Once the connection is verified, you can write Python code to read the temperature values measured by the DS18B20 sensor. Below is a sample code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import time

# Define the file path for the DS18B20 sensor
sensor_file = '/sys/bus/w1/devices/28-<device_id>/w1_slave'  # Replace <device_id> with the actual device ID

def read_temperature():
    try:
        # Open the sensor file
        with open(sensor_file, 'r') as file:
            lines = file.readlines()

            # Get the line containing the temperature value
            temperature_line = lines[1]
            
            # Extract the temperature value
            temperature = float(temperature_line.split('=')[1]) / 1000.0
            
            return temperature

    except IOError as e:
        print("Could not read from temperature sensor:", str(e))
        return None

# Loop to read temperature and print it
while True:
    temperature = read_temperature()
    if temperature is not None:
        print("Current Temperature:", temperature, "℃")
    time.sleep(1)  # Delay for 1 second

Make sure to replace <device_id> in the code above with the actual device ID of your DS18B20 sensor. You can find the correct device ID by running the command ls /sys/bus/w1/devices/.

The above code will continuously read the temperature and print it every second. You can modify and expand it as needed to fit your specific application.

Reading Temperature from DS18B20 Sensor Using Raspberry Pi and Python

By following these steps, you can easily read temperature values from the DS18B20 sensor using the Raspberry Pi and Python. This method provides a simple and reliable way to capture environmental temperature data for your projects. I hope this article helps you with reading temperature sensors in your Raspberry Pi projects!