Record temperature and humidity with systemd on Raspberry Pi

Thing you want to do

Record room temperature and humidity when Raspi4 starts up

Things necessary

H/W

The H / W used is as follows

  1. Raspberry Pi 4
  2. HDC1000

S/W

  1. Python 3.6.1 | packaged by rpi | (default, Apr 20 2017, 19:35:19)
  2. Linux raspi4 4.19.97-v7l+ #1294 SMP Thu Jan 30 13:21:14 GMT 2020 armv7l GNU/Linux

various settings

HDC1000 connection

スクリーンショット 2020-04-10 13.11.17.png

I couldn't find the parts for Raspberry Pi 4.

HDC1000 settings

/boot/config.txt

i2c related settings

dtparam=i2c_arm=on

/etc/modules

Module related settings

i2c-dev
i2c-bcm2835

Check HDC1000 settings

sh


$ lsmod | grep i2c
i2c_bcm2835            16384  0
i2c_dev                20480  0

sh


$ dmesg | grep i2c
[    2.153160] i2c /dev entries driver

sh


$ i2cdetect -l
i2c-1	i2c       	bcm2835 I2C adapter             	I2C adapter

$ i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: 40 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --

Operation check

This is a sample program.

python


# -*- coding: utf-8 -*-
import smbus
import time

# Get I2C bus
bus = smbus.SMBus(1)

# HDC1000 address, 0x40(64)
# Select configuration register, 0x02(02)
#        0x30(48)    Temperature, Humidity enabled, Resolultion = 14-bits, Heater on
bus.write_byte_data(0x40, 0x02, 0x30)

# HDC1000 address, 0x40(64)
# Send temp measurement command, 0x00(00)
bus.write_byte(0x40, 0x00)

time.sleep(0.2)

# HDC1000 address, 0x40(64)
# Read data back, 2 bytes
# temp MSB, temp LSB
data0 = bus.read_byte(0x40)
data1 = bus.read_byte(0x40)

# Convert the data
temp = (data0 * 256.000) + data1
cTemp = (temp / 65536.000) * 165.000 - 40.000

# HDC1000 address, 0x40(64)
# Send humidity measurement command, 0x01(01)
bus.write_byte(0x40, 0x01)
time.sleep(0.2)

# HDC1000 address, 0x40(64)
# Read data back, 2 bytes
# humidity MSB, humidity LSB
data0 = bus.read_byte(0x40)
data1 = bus.read_byte(0x40)


# Convert the data
humidity = (data0 * 256.000) + data1
humidity = (humidity / 65536.000) * 100.000

print('Humid.:' + str(humidity) + '%')
print('Temp. :' + str(cTemp) + '℃ ')

When executed, it will be as follows.


$ python HDC1000.py
Humid.:41.96014404296875%
Temp. :22.763748168945312℃

Recording program

The recording program looks like this.

python


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import smbus
import time
import datetime
import csv
import pathlib
import os

file_name = 'th_data.csv'
header_data = 'date_time,temperature\n'

def read_temp():
        # Get I2C bus
        bus = smbus.SMBus(1)
        # HDC1000 address, 0x40(64)
        # Select configuration register, 0x02(02)
        #        0x30(48)    Temperature, Humidity enabled, Resolultion = 14-bits, Heater on
        bus.write_byte_data(0x40, 0x02, 0x30)

        # HDC1000 address, 0x40(64)
        # Send temp measurement command, 0x00(00)
        bus.write_byte(0x40, 0x00)
        time.sleep(0.2)

        # HDC1000 address, 0x40(64)
        # Read data back, 2 bytes
        # temp MSB, temp LSB
        data0 = bus.read_byte(0x40)
        data1 = bus.read_byte(0x40)

        # Convert the data
        temp = (data0 * 256.000) + data1
        cTemp = (temp / 65536.000) * 165.000 - 40.000
        return cTemp

def read_humid():
        # Get I2C bus
        bus = smbus.SMBus(1)
        # HDC1000 address, 0x40(64)
        # Select configuration register, 0x02(02)
        #        0x30(48)    Temperature, Humidity enabled, Resolultion = 14-bits, Heater on
        bus.write_byte_data(0x40, 0x02, 0x30)

        # HDC1000 address, 0x40(64)
        # Send humidity measurement command, 0x01(01)
        bus.write_byte(0x40, 0x01)
        time.sleep(0.2)

        # HDC1000 address, 0x40(64)
        # Read data back, 2 bytes
        # humidity MSB, humidity LSB
        data0 = bus.read_byte(0x40)
        data1 = bus.read_byte(0x40)

        # Convert the data
        humidity = (data0 * 256.000) + data1
        humidity = (humidity / 65536.000) * 100.000
        return humidity


def file_check():
        global file_name
        file_name = pathlib.Path(file_name)
        if os.path.exists(file_name):
                print('Data File exists!')
        else:
                file_name.touch()
def header():
        global file_name
        with open(file_name) as f:
                line = f.readline()
        if 'date' in line:
                print('Header exists!')
        else:
                with open(file_name) as f:
                        lines = f.readlines()
                        lines.insert(0, header_data)
                        f.close()
                with open(file_name, mode='w') as f:
                        f.writelines(lines)

def main():
        global file_name
        file_check()
        header()
        while True:
                now = datetime.datetime.now()
                temp = read_temp()
                humid = read_humid()
#               print(now.strftime('%Y%m%d-%H:%M:%S'), '{:.3f}'.format(temp), '{:.3f}'.format(humid))
                save_data = [now.strftime('%Y%m%d-%H:%M:%S'), '{:.3f}'.format(temp), '{:.3f}'.format(humid)]
                with open(file_name,'a',newline='') as f:
                        writer = csv.writer(f, lineterminator='\r\n')
                        writer.writerow(save_data)
                time.sleep(10)

if __name__ == '__main__':
        main()

systemd settings and autostart settings

/etc/systemd/system/thlogger.service

I chose the service name thlogger.

[Unit]
Description=TH_Logger
After=syslog.target

[Service]
User = pi
PIDFile=/var/run/thlogger.pid
WorkingDirectory=/home/pi/Jupyter/data
ExecStart=/home/pi/berryconda3/bin/python /home/pi/works/HDC1000/TH_logger.py
ExecStop=/bin/kill $MAINPID
ExecReload=/bin/kill -HUP $MAINPID
Restart=always

RestartSec=10s
[Install]
WantedBy = multi-user.target
$ sudo systemctl daemon-reload
$ sudo systemctl start thlogger

Check the startup log (/ var / log / system)

$ sudo systemctl status thlogger.service -l
● thlogger.service - TH_Logger
   Loaded: loaded (/etc/systemd/system/thlogger.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2020-04-10 13:09:16 JST; 18min ago
 Main PID: 352 (python)
    Tasks: 1 (limit: 4915)
   Memory: 9.1M
   CGroup: /system.slice/thlogger.service
           └─352 /home/pi/berryconda3/bin/python /home/pi/works/HDC1000/TH_logger.py

April 10 13:09:16 raspi4 systemd[1]: Started TH_Logger.

If there is no problem, run it at startup.

$ sudo systemctl enable thlogger

Recommended Posts

Record temperature and humidity with systemd on Raspberry Pi
Get temperature and humidity with DHT11 and Raspberry Pi
Measure temperature and humidity with Raspberry Pi3 and visualize with Ambient
Raspberry + am2302 Measure temperature and humidity with temperature and humidity sensor
Ubuntu 20.04 on raspberry pi 4 with OpenCV and use with python
Troubleshoot with installing OpenCV on Raspberry Pi and capturing
MQTT on Raspberry Pi and Mac
Production of temperature control system with Raspberry Pi and ESP32 (1)
Measure and compare temperature with Raspberry Pi and automatically generate graph
Creating a temperature / humidity monitor with Raspberry Pi (pigpio version)
Pet monitoring with Rekognition and Raspberry pi
Easily make a TweetBot that notifies you of temperature and humidity with Raspberry Pi + DHT11.
Programming normally with Node-RED programming on Raspberry Pi 3
Working with sensors on Mathematica on Raspberry Pi
Detect temperature using python on Raspberry Pi 3!
Working with GPS on Raspberry Pi 3 Python
Measure temperature, humidity, etc. with SensorTag and send it to Ambient via Raspberry Pi 3 to graph it Part 2
Use BME280 temperature / humidity / barometric pressure sensor from Python on Raspberry Pi 2
[Python + PHP] Make a temperature / humidity / barometric pressure monitor with Raspberry Pi
Production of temperature control system with Raspberry Pi and ESP32 (2) Production of transmission device
Enjoy electronic work with GPIO on Raspberry Pi
MQTT RC car with Arduino and Raspberry Pi
Power on / off your PC with raspberry pi
Use Grove-Temperature & Humidity Sensor (DHT11) on Raspberry Pi
Play with your Ubuntu desktop on your Raspberry Pi 4
Display CPU temperature every 5 seconds on Raspberry Pi 4
Connect to MySQL with Python on Raspberry Pi
Measure CPU temperature of Raspberry Pi with Python
GPGPU with Raspberry Pi
pigpio on Raspberry pi
DigitalSignage with Raspberry Pi
Cython on Raspberry Pi
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
Machine learning with Raspberry Pi 4 and Coral USB Accelerator
Run LEDmatrix interactively with Raspberry Pi 3B + on Slackbot
Easy IoT to start with Raspberry Pi and MESH
Try debugging Python on Raspberry Pi with Visual Studio.
Detect mask wearing status with OpenCV and Raspberry Pi
Try using the temperature sensor (LM75B) on the Raspberry Pi.
Control brushless motors with GPIOs on Raspberry Pi Zero
Measure indoor and outdoor temperature and humidity and display on dashboard
Installation of Docker on Raspberry Pi and L Chika
Install pyenv on Raspberry Pi and version control Python
Getting Started with Yocto Project with Raspberry Pi 4 and WSL2
Simulate temperature measurement with Raspberry Pi + Flask + SQLite + Ajax
Control music playback on a smartphone connected to Raspberry Pi 3 and bluetooth with AVRCP
Build a server on Linux and local network with Raspberry Pi NextCloud and desktop sharing
Mutter plants with Raspberry Pi
Introduced pyenv on Raspberry Pi
Use NeoPixel on Raspberry Pi
Install OpenCV4 on Raspberry Pi 3
Install TensorFlow 1.15.0 on Raspberry Pi
Easy introduction to home hack with Raspberry Pi and discord.py
Create a web surveillance camera with Raspberry Pi and OpenCV
Python beginner opens and closes interlocking camera with Raspberry Pi
Create an LCD (16x2) game with Raspberry Pi and Python
I tried connecting Raspberry Pi and conect + with Web API
Detect "temperature (using A / D converter)" using python on Raspberry Pi 3!
I tried using the DS18B20 temperature sensor with Raspberry Pi
[Raspberry Pi] Stepping motor control with Raspberry Pi