[PYTHON] Creating a temperature / humidity monitor with Raspberry Pi (pigpio version)

Change GPIO control to pigpio and get temperature and humidity value from DHT22. I felt that it would be better to move to pigpio to control other sensors in the future, so I remade the one created with MyPyDHT.

Creating a temperature / humidity monitor with Raspberry Pi This is the pigpio version of.

Advance preparation

Install pigpio on your Raspberry Pi as shown on this web site. http://abyz.me.uk/rpi/pigpio/download.html

For the time being, just execute the command below.

sudo apt-get update
sudo apt-get install pigpio python-pigpio python3-pigpio

sudo pigpiod

The DHT control code was also on the pigpio author's Examples page and will be used as is. http://abyz.me.uk/rpi/pigpio/code/DHT.py

Use RasPi + FastAPI

Connection of DHT22 sensor and Raspberry Pi

The DAT terminal is connected to GPIO4, and 5V is given to VCC.

file organization

File Explanation
templates/index.html Get data every 5 seconds with HTML file and JavaScript
dht_server.py Includes sensor processing for Python server, DHT22
DHT.py pigpio author's DHT sensor control code (DHT11)/21/22/33/44) seems to be automatically supported

Main control of DHT22

If you execute the GPIO value with the DHT control code (DHT.py) as an argument, the greenhouse degree value will be acquired by the callback control if you add +100 to the GPIO value every 2 seconds.

python DHT.py 4
or
python DHT.py 104

Extract only the main process from DHT.py and write the code to get the greenhouse degree value every 2 seconds when it is executed. Save DHT.py in the same folder. You will post this code to the server later.

dht22_pigpio.py


import time
import DHT
import pigpio
import datetime

DHT_PIN = 4 

if __name__== "__main__":
    pi = pigpio.pi()
    if not pi.connected:
        print(f"cannot connect to pigpio")
        exit()

    s = DHT.sensor(pi, DHT_PIN)

    while True:
        try:
            d = s.read()
            today = datetime.datetime.fromtimestamp(d[0]).strftime ("%Y/%m/%d %H:%M" )
            temperature = d[3]
            humidity = d[4]
            dat = {"time": today, "temperature": temperature, "humidity": humidity}
            print(f"json: {dat}")
            time.sleep(2)
        except KeyboardInterrupt:
            break

    s.cancel()
    print(f"cancelling")
    pi.stop()

html code

Use fetch from the Python server to get temperature and humidity information every 5 seconds. (Same as last time)

index.html


<!DOCTYPE html>
<html lang="ja">

<head>
    <title>Temperature / humidity monitoring monitor</title>
</head>

<body>
    <div>
        <div class="container">
            <h1>Temperature / humidity monitoring monitor</h1>
            <h2 id="time">time</h2>
            <h2 id="temperature">temperature</h2>
            <h2 id="humidity">humidity</h2>
        </div>
    </div>
    <script>
        //Obtaining greenhouse degree value from server
        var sensor_read = function () {
            fetch("/data", {
                method: 'GET'
            }).then((response) => {
                return response.json();
            }).then((data) => {
                console.log(data);
                var time = document.querySelector("#time")
                time.innerHTML = data.time
                var temperature = document.querySelector("#temperature")
                temperature.innerHTML = `temperature:${data.temperature}Every time`
                var humidity = document.querySelector("#humidity")
                humidity.innerHTML = `Humidity:${data.humidity}%`
            }).catch((err) => {
                console.error(err);
            });
        };

     //5 second timer
        setInterval(sensor_read, 5000);
    </script>
</body>

</html>

Python code

Pass temperature/humidity data with Dict when accessing/data.

dht_server.py


import uvicorn
from fastapi import FastAPI
from starlette.templating import Jinja2Templates
from starlette.requests import Request
import datetime
import DHT
import pigpio

app = FastAPI()

templates = Jinja2Templates(directory="templates")
jinja_env = templates.env

DHT_PIN = 4 
sensor = None

@app.get("/")
def root(request: Request):
    return templates.TemplateResponse('index.html',
                                      {'request': request})

@app.get("/data")
def data():
    """Returns temperature and humidity values"""
    try:
        data = sensor.read()
        today = datetime.datetime.fromtimestamp(data[0]).strftime ("%Y/%m/%d %H:%M")
        status = data[2]
        temperature = data[3]
        humidity = data[4]
        if status == DHT.DHT_GOOD:
            dat = {"time": today, "temperature": temperature, "humidity": humidity}
            print(f"json: {dat}")
            return dat
        else:
            raise Exception(f"dht sensor error: {status}")
    except Exception as e:
        print(f"err: {str(e)}")

    return None


if __name__ == "__main__":
    pi = pigpio.pi()
    if not pi.connected:
        print(f"cannot connect to pigpio")
        exit()

    sensor = DHT.sensor(pi, DHT_PIN)
    #Server startup
    uvicorn.run(app, host="0.0.0.0", port=8000)

    sensor.cancel()
    print(f"cancelling")
    pi.stop()

Start the server.

Check the IP of the Raspberry Pi and access it with a browser. Please check 0.0.0.0 with ifconfig etc. on Raspberry Pi and replace it.

 $ python dht_server.py 

Recommended Posts

Creating a temperature / humidity monitor with Raspberry Pi (pigpio version)
[Python + PHP] Make a temperature / humidity / barometric pressure monitor with Raspberry Pi
Get temperature and humidity with DHT11 and Raspberry Pi
Record temperature and humidity with systemd on Raspberry Pi
Creating a temperature control system with Raspberry Pi and ESP32 (3) Recipient Python file
Using a webcam with Raspberry Pi
Easily make a TweetBot that notifies you of temperature and humidity with Raspberry Pi + DHT11.
Build a Tensorflow environment with Raspberry Pi [2020]
Make a wash-drying timer with a Raspberry Pi
Operate an oscilloscope with a Raspberry Pi
Create a car meter with raspberry pi
Raspberry + am2302 Measure temperature and humidity with temperature and humidity sensor
Measure CPU temperature of Raspberry Pi with Python
GPGPU with Raspberry Pi
pigpio on Raspberry pi
DigitalSignage with Raspberry Pi
Monitor temperature using Raspberry Pi + Alibaba cloud IoT platform
A memorandum when making a surveillance camera with Raspberry Pi
Simulate temperature measurement with Raspberry Pi + Flask + SQLite + Ajax
Mutter plants with Raspberry Pi
Create a web surveillance camera with Raspberry Pi and OpenCV
Detect "temperature (using A / D converter)" using python on Raspberry Pi 3!
Production of temperature control system with Raspberry Pi and ESP32 (1)
I tried using the DS18B20 temperature sensor with Raspberry Pi
Measure and compare temperature with Raspberry Pi and automatically generate graph
getrpimodel: Recognize Raspberry Pi model (A, B, B +, B2, B3, etc) with python
I made a surveillance camera with my first Raspberry PI.
Measure temperature, humidity, etc. with SensorTag and send it to Ambient via Raspberry Pi 3 to graph it Part 2
Control the motor with a motor driver using python on Raspberry Pi 3!
Let's make a cycle computer with Raspberry Pi Zero (W, WH)
I made a web server with Raspberry Pi to watch anime
Christmas classic (?) Lighting a Christmas tree with Raspberry Pi and Philips Hue
Notify LINE of body temperature from BLE thermometer with Raspberry Pi # 1
Make a thermometer with Raspberry Pi and make it viewable with a browser Part 4
Make a Kanji display compass with Raspberry Pi and Sense Hat
Raspberry Pi --1 --First time (Connect a temperature sensor to display the temperature)
[Note] Using 16x2-digit character LCD (1602A) from Python with Raspberry Pi
Use vl53l0x with Raspberry Pi (python)
Servo motor control with Raspberry Pi
Creating a decision tree with scikit-learn
Creating a Flask server with Docker
Serial communication with Raspberry Pi + PySerial
OS setup with Raspberry Pi Imager
Creating a simple app with flask
Try L Chika with raspberry pi
VPN server construction with Raspberry Pi
A memo to simply use the illuminance sensor TSL2561 with Raspberry Pi 2
Detect analog signals with A / D converter using python on Raspberry Pi 3!
[Electronic work] I made a Suica touch sound detector with Raspberry Pi
Make a wireless LAN Ethernet converter and simple router with Raspberry Pi
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
Create a socket with an Ethernet interface (eth0, eth1) (Linux, C, Raspberry Pi)
[Detailed version] Creating a comfortable Python environment with Google Compute Engine (Ubuntu 16.04)
Production of temperature control system with Raspberry Pi and ESP32 (2) Production of transmission device
Measure SIM signal strength with Raspberry Pi
Pet monitoring with Rekognition and Raspberry pi
Creating a simple PowerPoint file with Python
Hello World with Raspberry Pi + Minecraft Pi Edition
Get BITCOIN LTP information with Raspberry PI
Try fishing for smelt with Raspberry Pi
Programming normally with Node-RED programming on Raspberry Pi 3