[PYTHON] I tried using the DS18B20 temperature sensor with Raspberry Pi

Summary of this article

After connecting the DB18B20 sensor to the Raspberry Pi3B + and getting the temperature with a Python script, I got the temperature regularly with crontab.

What is the DB18B20 sensor?

The DB18B20 sensor is an inexpensive sensor that can acquire temperature without using an analog converter between the sensor and Raspberry Pi. If you want to measure the temperature (or humidity) in the air in terms of the amount of information and the price, the dht11 sensor or this upward compatible dht22 sensor can be said to be the best. However, the biggest merit of DB18B20 is that the waterproof type is on sale and the water temperature can be measured. By the way, is the author made in China called HiLetgo? I bought 5 items for about 1000 yen on Amazon.

environment

devices: Raspberry Pi3B+ OS: Rasbian NOOBS_ver_3_5_1 Language: Python 3 series

circuit

Regarding the circuit, I referred to the following URL. http://aba.doorblog.jp/archives/55110922.html Thank you for posting the circuit. However, it is only via a pull-down resistor. The point is to connect the signal line (generally yellow) to GPIO4! You can change it, but this time I did it. In the case of the author, I had only 2kΩ at hand, so I used this, but no error was found in the measurement results. In addition, since the Raspberry Pi has a resistance on the main body, it seems that it is not necessary to go through this resistance.

Preparation

This sensor seems to use a communication method that uses an interface called 1-wire. So turn this on. First, enter the following command in the terminal.

$sudo nano /boot/config.txt

The nano here is an editor specification, but of course you can use a different editor if you like. The editor will open, so add the following at the bottom.

$dtoverlay=w1-gpio

If you do this, restart Raspberry Pi with sudo reboot. If you turn on 1-wire in Raspberry Pi Desktop> Raspberry Pi Settings> Interface, all the above work will be completed with GUI (yes, no).

Next, also at the terminal

$lsmod

Enter. Here, check the next of the tenth line from the bottom.

w1_therm               24576  0
w1_gpio                16384  0
fixed                  16384  0
wire                   36864  2 w1_gpio,w1_therm
cn                     16384  1 wire
uas                    24576  0
uio_pdrv_genirq        16384  0
uio                    20480  1 uio_pdrv_genirq
i2c_dev                20480  0
ip_tables              28672  0
x_tables               32768  1 ip_tables
ipv6                  458752  46

To be honest, I don't really understand what this means, but if there is a description of w1_therm, w1_gpio, it seems OK. If this doesn't appear, make sure the 1-wire interface is properly turned on and the pull-down resistor is properly engaged. I flew for an hour because the circuit was wrong.

Then do the following in your terminal:

$sudo modprobe w1-gpio
$sudo modprobe w1-therm

Next, go to check the ID of the sensor. Enter the following path in the terminal to move the directory.

$ cd /sys/bus/w1/devices/

After moving, do the following:

$ ls -la

Then, the following information is obtained.

drwxr-xr-x 2 root root 0 December 30 10:20 .
drwxr-xr-x 4 root root 0 December 30 10:20 ..
lrwxrwxrwx 1 root root 0 December 30 10:26 28-3c01b5564493 -> ../../../devices/w1_bus_master1/28-3c[The number string displayed on your screen]
lrwxrwxrwx 1 root root 0 December 30 10:20 w1_bus_master1 -> ../../../devices/w1_bus_master1

Here, read the number at 28-3c ... Memo memo because I will use it later. If you don't know the number 28, go back to reconfirming whether the circuit diagram points to the signal line to GPIO4 or 1-wire is turned on.

Next is the operation test. Please enter the following path in the terminal.

$/sys/bus/w1/devices/28-[The number you took note of above]

At the destination, do the following

/sys/bus/w1/devices/28-3c01b5564493 $ cat w1_slave

Then, you will get something like this ↓.

a7 00 55 05 7f a5 a5 66 a5 : crc=a5 YES
a7 00 55 05 7f a5 a5 66 a5 t=10437

t = 10437 is the temperature. The value divided by 1000 is the temperature. 10.437 ° C. Yeah, my house is cold, lol.

This completes the preparation. If it gets stuck (1) Check the 1-wire settings. Did you forget to reboot? (2) Check the circuit. In this flow, it is necessary to select GPIO4 as the communication line. (3) The temperature sensor itself is dead. Since it is made in China, it remains as it is, so I will change each sensor.

Make a python script

Next, since the above preparations have been completed, we will create a program that measures the temperature with Python and records the measurement data in a csv file with the date and time. The created program is as follows.

import datetime
import os 

#Please change the file pass here to your arbitrary user name or desired file storage location (pi → tarou)
fileName = '/home/pi/waterTemp/waterTemp.csv'

#It is written with with statement, but it does not have to be this separately
with open('/sys/bus/w1/devices/28-[Your sequence]/w1_slave') as f:
    #print(type(f))
    data = f.read()
    waterTemp = float(data[data.index('t=')+2:])/1000
    
#print(waterTemp)

#If there is no file in the relevant part, create it
if not os.path.exists(fileName):
    thData = open(fileName,'w')
    thData.write('date_time,waterTemp\n')
    thData.close()

#Processing to record temperature data over time
while True:
    now = str(datetime.datetime.now())[0:16]
    data = [now,waterTemp]
    if waterTemp == 0:
        continue
    thData = open(fileName, 'a')
    thData.write(','.join(map(str,data))+'\n')
    thData.close()
    print(','.join(map(str,data)))
    break

This time, I wrote it in Thonny.

Get temperature data regularly with cron

Finally, run the Python script created above with cron on a regular basis. It seems that cron is relatively easy, but I'm a beginner, so I'm surprised that I'm stuck, so I'd like to write a detailed article again. This time, I will briefly describe the flow.

Enter the following in the terminal.

crontab -e

Select your favorite editor (nano is the one for me. I think it's easy.) Write as follows at the bottom.

# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command
#Add the following items! !!
*/1 * * * * /usr/bin/python3 /home/pi/waterTemp/waterTemp.py

For the path, specify the location where the script is placed. Now press y with ctrl -x to finish. This time, the */1 * * * * part is acquired every minute, but please change it appropriately.

At the end

This time, I connected the DS18B20 sensor to the Raspberry Pi and did DIY to save the temperature in csv on a regular basis. With this, it seems to be fun to use for IoT work such as visualization of the water temperature of ornamental fish and the nutrient solution temperature of hydroponics. Heppoko is a groping work for science university students, so I would appreciate it if you could share any mistakes or if you think that this is smarter.

References

Thank you very much for the following sites and books. Thank you very much. https://www.taneyats.com/entry/raspi-smart-aquarium-2 https://dkpyn.com/blog/2344 https://kookye.com/ja/2017/06/01/desgin-a-temperature-detector-through-raspberry-pi-and-ds18b20-temperature-sensor/ You can understand from scratch! Raspberry Pi Introductory Guide to Electronic Work First Edition by Tatra Edit p189, p190

Recommended Posts

I tried using the DS18B20 temperature sensor with Raspberry Pi
Using the digital illuminance sensor TSL2561 with Raspberry Pi
Try using the temperature sensor (LM75B) on the Raspberry Pi.
Using the 1-Wire Digital Temperature Sensor DS18B20 from Python on a Raspberry Pi
I tried to automate the watering of the planter with Raspberry Pi
I wanted to run the motor with Raspberry Pi, so I tried using Waveshare's Motor Driver Board
I tried L-Chika with Raspberry Pi 4 (Python edition)
I connected the thermo sensor to the Raspberry Pi and measured the temperature (Python)
I tweeted the illuminance of the room with Raspberry Pi, Arduino and optical sensor
I tried using the Python library from Ruby with PyCall
I tried running Movidius NCS with python of Raspberry Pi3
When I tried to do socket communication with Raspberry Pi, the protocol was different
I tried connecting Raspberry Pi and conect + with Web API
I tried to automate [a certain task] using Raspberry Pi
Using a webcam with Raspberry Pi
I tried using the checkio API
I tried using the Pi Console I / F of the Raspberry Pi IoT starter kit "anyPi" from Mechatrax.
I tried to move ROS (Melodic) with the first Raspberry Pi (Stretch) at the beginning of 2021
I tried to make a motion detection surveillance camera with OpenCV using a WEB camera with Raspberry Pi
Control the motor with a motor driver using python on Raspberry Pi 3!
I learned how the infrared remote control works with Raspberry Pi
Raspberry Pi --1 --First time (Connect a temperature sensor to display the temperature)
Periodically log the value of Omron environment sensor with Raspberry Pi
Use the Grove sensor on the Raspberry Pi
Improved motion sensor made with Raspberry Pi
I tried to estimate the pi stochastically
I tried playing with the image with Pillow
Use PIR motion sensor with raspberry Pi
Detect temperature using python on Raspberry Pi 3!
I tried using the BigQuery Storage API
Note: I want to do home automation with Home Assistant + Raspberry Pi + sensor # 1
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
I tried using "Streamlit" which can do the Web only with Python
Logging the value of Omron environment sensor with Raspberry Pi (USB type)
I tried "smoothing" the image with Python + OpenCV
I tried using scrapy for the first time
vprof --I tried using the profiler for Python
I tried "differentiating" the image with Python + OpenCV
I tried to save the data with discord
I tried using PyCaret at the fastest speed
I tried using the Google Cloud Vision API
I tried using mecab with python2.7, ruby2.3, php7
I tried "binarizing" the image with Python + OpenCV
I tried using the Datetime module by Python
Observe the Geminids meteor shower with Raspberry Pi 4
Sound the buzzer using python on Raspberry Pi 3!
Raspberry + am2302 Measure temperature and humidity with temperature and humidity sensor
Get temperature and humidity with DHT11 and Raspberry Pi
I tried using the image filter of OpenCV
I tried DBM with Pylearn 2 using artificial data
I tried using the functional programming library toolz
I tried using a database (sqlite3) with kivy
I tried playing with the calculator on tkinter
Measure CPU temperature of Raspberry Pi with Python
I tried Hello World with 64bit OS + C language without using the library
I tried to build an environment of Ubuntu 20.04 LTS + ROS2 with Raspberry Pi 4
I tried running Flask on Raspberry Pi 3 Model B + using Nginx and uWSGI
[For beginners] I made a motion sensor with Raspberry Pi and notified LINE!
I tried to create a button for Slack with Raspberry Pi + Tact Switch
I tried using parameterized
I tried using argparse