0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ラズベリーパイで気温・湿度監視モニターの作成

Posted at

事前準備

RasPi+FastAPIを使う
RasPi+PythonでDHT22を動かす

ファイル構成

ファイル 説明
templates/index.html HTMLファイル、JavaScriptで5秒ごとにデータを取得する
dht_server.py Pythonサーバ、DHT22のセンサー処理を含む 

html code

Pythonサーバからfetchを使用して5秒ごとに気温と湿度情報を取得する。

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

<head>
    <title>気温・湿度監視モニター</title>
</head>

<body>
    <div>
        <div class="container">
            <h1>気温・湿度監視モニター</h1>
            <h2 id="time">time</h2>
            <h2 id="temperature">temperature</h2>
            <h2 id="humidity">humidity</h2>
        </div>
    </div>
    <script>
        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 = `気温:${data.temperature}度`
                var humidity = document.querySelector("#humidity")
                humidity.innerHTML = `湿度:${data.humidity}%`
            }).catch((err) => {
                console.error(err);
            });
        };

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

</html>

Python code

/dataへアクセスした時にDictで気温・湿度データを渡す。

dht_server.py
import uvicorn
from fastapi import FastAPI
import RPi.GPIO as GPIO
import MyPyDHT
from starlette.templating import Jinja2Templates
from starlette.requests import Request
import datetime

app = FastAPI()

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

GPIO.setmode(GPIO.BCM)
DHT_PIN = 4 
GPIO.setup(DHT_PIN,GPIO.OUT)

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

@app.get("/data")
def data():
    try:
        today = datetime.datetime.now().strftime ("%Y/%m/%d %H:%M" ) 
        humidity, temperature = MyPyDHT.sensor_read(MyPyDHT.Sensor.DHT22, DHT_PIN, use_cache=True)
        if humidity is not None and temperature is not None:
            dat = {"time": today, "temperature": temperature, "humidity": humidity}
            print(f"json: {dat}")
            return dat
    except MyPyDHT.DHTException as e:
        print(f"err: {str(e)}")
    return None


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

サーバを起動する。

ラズベリーパイのIPを調べて、ブラウザでアクセスする。
0.0.0.0はラズベリーパイ上でifconfigなどで調べて置き換えてください。

 $ python dht_server.py 
INFO:     Started server process [5720]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?