Using the 1-Wire Digital Temperature Sensor DS18B20 from Python on a Raspberry Pi

Python on Adafruit's Raspberry Pi Lesson 11. DS18B20 Temperature Sensing on Adafruit's Lern site, which I always refer to. There was a sample of temperature sensing of DS18B20 using. The W1ThermSensor library is introduced as an easy method, so let's try it. The license is GPLv2.

1-Wire setup

Check the kernel version.

$ uname -a
Linux raspberrypi 3.18.11+ #777 PREEMPT Sat Apr 11 17:24:23 BST 2015 armv6l GNU/Linux

The kernel is as described in 1-Wire in Parasite Power configuration (1-Wire using 2 wires) does not work in 3.18.3 # 348. For 3.18.1 + and above, the setting to enable 1-Wire has been changed. Add the following line to /boot/config.txt and reboot.

/boot/config.txt


dtoverlay=w1-gpio-pullup,gpiopin=4

How to read w1_slave files directly

First, try reading the w1_slave file under/ sys / bus / w1 / devices /from your Python code.

~/python_apps/w1-test.py


# -*- coding: utf-8 -*-
import os
import glob
import time
import subprocess

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
    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')
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][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
	
while True:
    s = "celsius: {0:.3f}, fahrenheit: {1:.3f}"
    temp = read_temp()
    print(s.format(*temp))
    time.sleep(5)

Run the program. I got Celsius and Fahrenheit and formatted them with 3 decimal places.

$ python w1-test.py
celsius: 27.312, fahrenheit: 81.162
celsius: 27.687, fahrenheit: 81.837
celsius: 27.500, fahrenheit: 81.500

How to use W1ThermSensor

Install W1ThermSensor by git clone.

$ cd ~/python_apps
$ git clone https://github.com/timofurrer/w1thermsensor.git 
$ cd w1thermsensor
$ sudo python setup.py install

Write a simple program. Sensing data can be acquired with a float with 3 digits after the decimal point.

~/python_apps/w1-test.py


# -*- coding: utf-8 -*-
from w1thermsensor import W1ThermSensor

sensor = W1ThermSensor()
celsius = sensor.get_temperature()
fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F)
all_units = sensor.get_temperatures([W1ThermSensor.DEGREES_C, W1ThermSensor.DEGREES_F, W1ThermSensor.KELVIN])

print("celsius:    {0:.3f}".format(celsius))
print("fahrenheit: {0:.3f}".format(fahrenheit))
s = "celsius: {0:.3f}, fahrenheit: {1:.3f}, kelvin: {2:.3f}"
print(s.format(*all_units))

Run the program. The code is simplified because the library takes care of reading the w1_slave file from the / sys / bus / w1 / devices directory as in the first example.

$ python w1-test.py
celsius:    26.625
fahrenheit: 79.925
celsius: 26.625, fahrenheit: 79.925, kelvin: 299.775

Recommended Posts

Using the 1-Wire Digital Temperature Sensor DS18B20 from Python on a Raspberry Pi
Try using the temperature sensor (LM75B) on the Raspberry Pi.
Detect "temperature (using A / D converter)" using python on Raspberry Pi 3!
I tried using the DS18B20 temperature sensor with Raspberry Pi
Detect temperature using python on Raspberry Pi 3!
Control the motor with a motor driver using python on Raspberry Pi 3!
Sound the buzzer using python on Raspberry Pi 3!
Use BME280 temperature / humidity / barometric pressure sensor from Python on Raspberry Pi 2
Detect "brightness" using python on Raspberry Pi 3!
Use the Grove sensor on the Raspberry Pi
Run servomotor on Raspberry Pi 3 using python
[Note] Using 16x2-digit character LCD (1602A) from Python with Raspberry Pi
About the error I encountered when trying to use Adafruit_DHT from Python on a Raspberry Pi
Detect analog signals with A / D converter using python on Raspberry Pi 3!
I connected the thermo sensor to the Raspberry Pi and measured the temperature (Python)
Try using a QR code on a Raspberry Pi
Detect magnet switches using python on Raspberry Pi 3!
Build a Python development environment on Raspberry Pi
Finally ... Make a radio control using python on Raspberry Pi 3! (The motor moves while the button is pressed)
[Raspberry Pi] Publish a web application on https using Apache + WSGI + Python Flask
Output to "7-segment LED" using python on Raspberry Pi 3!
A little bit from Python using the Jenkins API
Finally ... Make a radio control using python on Raspberry Pi 3! (The motor moves while the magnet is brought closer)
[Don't refer to 04.02.17] Display the temperature sensor on a real-time graph with rasberry pi 3.
Install PyCall on Raspberry PI and try using GPIO's library for Python from Ruby
Access google spreadsheet using python on raspberry pi (for myself)
How to get temperature from switchBot thermo-hygrometer using raspberry Pi
Notes on using MeCab from Python
Using a webcam with Raspberry Pi
Make a simple CO2 incubator using Raspberry PI and CO2 sensor (MH-Z14A)
Use python on Raspberry Pi 3 to illuminate the LED (Hello World)
Finally ... Make a radio control using python on Raspberry Pi 3! (When the magnet is brought closer, the motor moves and stops automatically)
A memo to simply use the illuminance sensor TSL2561 with Raspberry Pi 2
Adafruit Python BluefruitLE works on Raspberry Pi.
Use python on Raspberry Pi 3 to light the LED with switch control!
Try tweeting arXiv's RSS feed on twitter from Raspberry Pi with python
[Python + PHP] Make a temperature / humidity / barometric pressure monitor with Raspberry Pi
[Python] A progress bar on the terminal
Working with GPS on Raspberry Pi 3 Python
The temperature is automatically measured using Raspberry Pi 3 and automatically uploaded to the server (Docker python3 + bottle + MySQL) for viewing!
[2015/11/19] How to register a service locally using the python SDK on naoqi os
Make a thermometer with Raspberry Pi and make it visible on the browser Part 3
Creating a temperature control system with Raspberry Pi and ESP32 (3) Recipient Python file
Use python on Raspberry Pi 3 and turn on the LED when it gets dark!
Use Raspberry Pi Python to TMP36 analog temperature sensor and MCP3008 AD converter
Build a Django environment on Raspberry Pi (MySQL)
Python: Try using the UI on Pythonista 3 on iPad
Send data from Raspberry Pi using AWS IOT
Make DHT11 available on Raspberry Pi + python (memo)
Operate the schedule app using python from iphone
Run a Python file from html using Django
Create a visitor notification system using Raspberry Pi
Display CPU temperature every 5 seconds on Raspberry Pi 4
Run a python script from excel (using xlwings)
Connect to MySQL with Python on Raspberry Pi
Create a GUI on the terminal using curses
Measure CPU temperature of Raspberry Pi with Python
I made a Python program for Raspberry Pi that operates Omron's environmental sensor in the mode with data storage
Realize a super IoT house by acquiring sensor data in the house with Raspberry Pi
A note on the library implementation that explores hyperparameters using Bayesian optimization in Python
Use kintone API SDK for Python on Raspberry Pi (easily store data in kintone from Raspberry Pi)