The Yocto Project on Raspberry Pi 5 Episode 10: 1-Wire and DS18B20 Temperature Sensor
This step-by-step tutorial explains how to enable and use the 1-Wire (W1) interface on a Raspberry Pi running a custom Linux distribution built with the Yocto Project and OpenEmbedded. The examples are based on the Yocto Long-Term Support (LTS) release Scarthgap and use the meta-raspberrypi Board Support Package (BSP) layer.
The 1-Wire communication protocol was originally developed by Dallas Semiconductor (now Maxim Integrated) and is widely used for connecting low-speed devices such as temperature sensors, identification chips, and small EEPROMs using a single data line and ground. It provides a simple and low-cost interface for applications that do not require the higher speed or complexity of I2C or SPI. One of the most popular 1-Wire devices is the DS18B20 digital temperature sensor, which is often used in embedded and IoT projects for precise temperature measurements.
Follow the steps below to enable 1-Wire on Raspberry Pi and use it with a DS18B20 sensor on your Yocto-built image.
Step 1: Enable 1-Wire in Yocto
To enable the 1-Wire interface in your Yocto image, open the configuration file:
conf/local.conf
Then add the following line:
ENABLE_W1 = "1"
This configuration ensures that the Linux kernel modules required for the 1-Wire interface are enabled for your Raspberry Pi target platform.
Step 2: Include Python 3 Packages
In the examples, Python 3 is used to read data from the DS18B20 temperature sensor. To include Python 3 core and shell support in your image, append the following line to conf/local.conf:
After updating your configuration, build the base image by running:
bitbake core-image-base
When the build process completes, flash the generated image to a microSD card, insert it into your Raspberry Pi, and boot up the system.
Step 4: Measure Temperature Using DS18B20
Once your Raspberry Pi is running, you can access the temperature readings directly from the system file interface. Run the following command to read and display the temperature data from the DS18B20 sensor:
cat /sys/bus/w1/devices/28-*/w1_slave
This command outputs raw sensor data that includes the temperature value in Celsius.
Step 5: Read Temperature Data with Python
You can also read the DS18B20 temperature data using Python. Run the following code snippet in the Python 3 interactive shell to measure and print the temperature:
The hardware used in this demo is the ANAVI Gardening uHAT, an open-source Raspberry Pi add-on board designed for home automation, gardening and agriculture applications. It features connectors for multiple sensors and supports 1-Wire, ADC through SPI and I2C interfaces, making it ideal for monitoring temperature, soil moisture, and other environmental conditions. It is also available at Mouser Electronics.