Tested on:RPi3; Raspbian Stretch; Python3
Prerequisites:Raspberry Pi with Raspbian Jessie and internet connection (see steps 1-7 in the Introduction)
Hardware:4.7k Ohm Resistor
Breadboard and jumper cables

Measuring and logging temperature with the 1-Wire sensor DS18B20 and a Raspberry Pi

An interesting alternative for the quite expensive temperature sensor DHT22 is the 1-Wire sensor DS18B20 (data sheet) at half the price but without the capability to measure humidity. 1-Wire is a communication bus that supports reading a large number of sensors from a single wire.

Breadboard circuit
Turn off the Raspberry Pi, then connect it with the following circuit:

DS18B20 circuit

DS18B20 circuit

Connect the leftmost pin of the sensor to pin 6 (GND), the middle one over a pullup resistor of 4.7k Ohm to pin 7 and the rightmost pin to pin 1 (3.3V) of the Raspberry Pi in BOARD numbering.

Open the file config.txt with

and add at the end of the file the following line:

Enter in the terminal

Temperature measurement
Download the sample script with

and execute it:

The current temperature is written to the terminal.

Temperature logging
For logging temperature indefinitely, start the script with the parameter log:

The temperature is fetched every 5 seconds and stored in the Numpy format .npy for a subsequent evaluation.

Code explained
Every sensor is represented as a directory in /sys/bus/w1/devices/. Each directory has a file w1_slave with the result of the latest measurement:

DS18B20 Output

DS18B20 Output

The temperature sensor is implemented as a Python class which takes the target directory, the filename and a default value for temperature measurements as arguments:
The module glob allows resolving the linux * syntax:
The directory of a temperature sensor always begins with 28, followed by a sensor id in hex. Since only one sensor is attached, 28* fits its path. Then the file with the latest measurement result is loaded into data.
extracts the temperature (all characters after t=) and converts to Celsius.

Full script
Click on Full Script to show all of the code.

temperature sensor DHT22: http://www.knight-of-pi.org/measure-temperature-and-humidity-with-the-sensor-dht22-am2302/
1-Wire Wiki: https://en.wikipedia.org/wiki/1-Wire
Maxim Integrated DS18B20 data sheet: https://datasheets.maximintegrated.com/en/ds/DS18B20.pdf

Knight of Pi

Johannes Bergs aka Knight of Pi. Diploma in Bioinformatics, some Webdesign and Python coding then. Living in the beautiful city of Vienna.


Time limit is exhausted. Please reload CAPTCHA.