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.
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
The DAT terminal is connected to GPIO4, and 5V is given to VCC.
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 |
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()
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