For those who are already familiar with Raspberry Pi, you might be aware of one of its limitations – the absence of an Analog to Digital Converter (ADC). This means it can’t directly receive and interpret signals from analog sensors. To address this limitation, using the DS18B20 as an alternative to the TMP36 and integrating it with the Raspberry Pi emerges as a superior choice for creating a temperature detection device.
The DS18B20 is a digital temperature sensor that provides temperature data in a digital format without the need for an additional analog-to-digital converter. It comprises a packaged semiconductor head and three pins. Notably, Raspberry Pi operating systems, including Occidentalis and Raspbian systems from December 2012 onwards, already offer support for the DS18B20 1 wire temperature sensor. In this section, TechSparks will walk you through configuring and utilizing the DS18B20 temperature sensor on a Raspberry Pi, enabling you to precisely acquire temperature data. Let’s dive in!
This is a simple temperature sensor project that won’t cost you much. To get started with your project, you’ll need the following components:
- Raspberry Pi
- Extension Wire
- 4.7k-10k Ohm Resistor
- Jumper Wires
- Expansion Board
DS18B20 Raspberry Pi Wiring
In the diagram below, you can see how the Raspberry Pi is connected to the DS18B20 temperature sensor. The DS18B20 one-wire sensor’s connection method differs from most sensors on the market, as it uses a serial connection instead of a parallel one. This type of connection helps reduce interference and timing issues in data transmission. More importantly, it allows multiple DS18B20 sensors to share the same data line, reducing the number of required pins and cable complexity. Therefore, in this project, you only need a 4.7k-ohm resistor for the connection.
In a serial connection, the resistor’s role is to maintain the voltage of the data line. By pulling up the voltage on the data line, fluctuations in current within the circuit will significantly decrease, which is crucial to ensuring the DS18B20 sensor accurately measures temperature and transfers data to the Raspberry Pi.
Although this project doesn’t have a high level of technical difficulty, one easily overlooked detail is the orientation of the sensor. If not careful and the sensor is installed upside down, it could potentially damage the sensor. In the diagram, the curved part of the DS18B20 sensor faces upwards.
The wiring for different versions of the DS18B20 sensor may vary slightly, but the common point is that you need to connect a resistor between the 3.3V and data pins. The specific resistor value may vary depending on the circumstances.
- Waterproof Version: You only need to connect the red, black, and yellow wires; there’s no need to connect the additional pin at the bottom of the sensor.
- High-Temperature Version: It includes orange, white, blue wires, and an additional pin at the bottom. In this case, you should connect the orange wire to the 3.3V power source, the white wire to the GND, and the blue wire to pin 4 on the Raspberry Pi.
Although the DS18B20 may not appear remarkable from the outside, its internal design is both precise and intricate, consisting of several key components:
Temperature Sensor: Composed of a tiny silicon chip or similar material designed to detect changes in the surrounding environment’s temperature.
Single-Wire Serial Interface: Allows communication with the DS18B20 and provides temperature data in digital form.
Logic Control Unit: Handles and encodes signals from the temperature sensor for transmission to external devices.
Output Pins: Comprises three pins – one for power supply, one for grounding, and one for data communication.
Before deploying the DS18B20 sensor in an actual project with a Raspberry Pi, TechSparks recommends validating its functionality using command-line or SSH to avoid potential issues later.
To learn how to communicate with the DS18B20, execute the following commands in your terminal window. Please note that the subdirectory names under the “devices” directory may differ based on your system, so make the necessary adjustments according to your actual situation:
sudo modprobe w1-gpio
sudo modprobe w1-therm
cd 28-xxxx (change this to match what serial number pops up)
The communication interface of the DS18B20 can be somewhat unstable, and it may not always successfully transmit temperature data. Fortunately, the system reports whether temperature data is available for reading. These temperature data are actually stored in the Raspberry Pi’s file system in the form of files, and we can obtain temperature information by reading these files.
In the returned information, the “YES” or “NO” at the end of the first line indicates the status of sensor communication. If it’s “YES,” the communication was successful; if it’s “NO,” it means communication failed. When communication is successful, you will find temperature data in the second line. These temperature values are in units of 1/1000 degrees Celsius. In the provided example, the measured temperatures are 20.687 degrees Celsius and 26.125 degrees Celsius, respectively. This means you need to divide these numbers by 1000 to obtain the actual temperature values.
If you have connected multiple sensors, each sensor will create a folder named “28-xxx” in the /sys/bus/w1/devices directory. These folder names are unique but may be numerous. When you insert a new sensor, the system generates a new folder, and the “28-xxx” part will vary for each sensor. This is the unique identifier for each sensor. To differentiate which sensor corresponds to each folder, you can check the names of the newly generated folders and label each sensor with an identifier, such as its location or purpose. This ensures that when reading temperature data, you know from which sensor you are obtaining data, allowing you to accurately identify and record temperature information for different locations or purposes.
DS18B20 Raspberry Pi Code
Connect the Raspberry Pi with the DS18B20 temperature sensor, continuously retrieve and display temperature data in both Celsius and Fahrenheit. If there’s a failure in reading data, the program will wait for 0.2 seconds before attempting again, ensuring that valid temperature data is obtained.
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')
device_file = device_folder + '/w1_slave'
f = open(device_file, 'r')
lines = f.readlines()
lines = read_temp_raw()
while lines.strip()[-3:] != 'YES':
lines = read_temp_raw()
equals_pos = lines.find('t=')
if equals_pos != -1:
temp_string = lines[equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_c, temp_f
At the beginning of the program, the modprobe command is executed to enable the interface.
The following three lines are used to identify which files can be read from.
One potential issue when reading temperatures under Raspbian is freezing. In some cases, attempting to read sensor data using the original read_temp_raw method might cause the code to become unresponsive, possibly due to IO operations blocking.
To address this issue, it is recommended to use the subprocess module to run an external command that employs the cat command to read sensor data files, then capture the output of the command. The benefit of doing this is that if the cat command cannot complete for some reason, Python code won’t be blocked but will continue executing.
catdata = subprocess.Popen(['cat',device_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,err = catdata.communicate()
out_decode = out.decode('utf-8')
lines = out_decode.split('\n')
The temperature results include both Celsius and Fahrenheit values. You can use the variables deg_c and deg_f to store these two values separately for further processing or display. In the code, we obtain and assign these two values from the read_temp() method to these variables:
deg_c, deg_f = read_temp()
The main function of your program is to continuously read the temperature in a loop and print it, then wait for one second before executing again. To run this program on your Raspberry Pi, you’ll first need to transfer the program file to the Raspberry Pi’s file system. It’s recommended to use the SSH protocol to connect to your Raspberry Pi via the command line, which will allow you to execute commands and edit files on the Raspberry Pi.
Create or edit a file named “thermometer.py.” You can do this by entering the following command in the command line:
After pressing Ctrl+X, the editor will prompt you to save your changes. Press Y to confirm saving and then press Enter. This ensures that your program is saved to the file “thermometer.py” for running on the Raspberry Pi.
Before running the DS18B20 Raspberry Pi program, you need to execute the following command with superuser privileges:
sudo python thermometer.py
This will run the Python program with administrative privileges. If everything is working correctly, you’ll see a series of outputs similar to the following on the terminal. You can also place your finger on the temperature sensor to raise the temperature and ensure the sensor is functioning correctly.
Furthermore, you can connect multiple DS18B20 sensors to the Raspberry Pi’s VCC, data, and ground pins in parallel, using just one 4.7k resistor. Each sensor will create a unique /sys/bus/w1/devices/28-nnnnn directory, where “nnnnn” is the unique serial number of the sensor. However, the current Python program can only read data from one sensor. If you want to read data from multiple sensors simultaneously, you would need to modify the program to support reading from multiple sensors.
More content you may be interested in
This tutorial guides precision drone landing with Raspberry Pi, covering ROS Kinetic, MAVROS, and PX4 Autopilot setup. It explains Gazebo config, showcasing landmark recognition via
This collaborative project seamlessly integrates the Raspberry Pi 4B and STM32 to create a sophisticated Intelligent Access Control System. Leveraging the strengths of each component,
This tutorial streamlines Raspberry Pi’s auto-connect feature by editing the wpa_supplicant.conf file, allowing users to specify preferred Wi-Fi networks. By customizing network configurations, it ensures
This tutorial provides a concise guide to establishing SPI communication between a Raspberry Pi and an SSD1306 OLED display. It covers SPI principles, Raspberry Pi
Automating program startup on the Raspberry Pi can be achieved through various methods. Editing the “/etc/rc.local” file or using desktop applications, while simpler, may not
Raspberry Pi, a revolutionary single-board computer introduced by the Raspberry Pi Foundation, has become a global sensation, initially designed for educational purposes. With its integrated