DHT11/12網路監測溫濕度計-micropython


DHT11/12網路監測溫濕度計-micropython

tags: micropython dht11/12 webserver

DHT11/12單純測試參考頁面-

https://blairan-esp32-micropython.blogspot.com/2021/07/dht11dht12-micropython.html

WiFi聯網參考-https://blairan-esp32-micropython.blogspot.com/2021/07/wifi.html


完整程式碼

import dht

import network, socket

from machine import Pin

from time import sleep

  

ssid="---"

password="------"

STA=network.WLAN(network.STA_IF)

STA.active(True)

STA.connect(ssid, password)


while STA.isconnected()==False:

    pass

print("The connected successful!")

print("IP:  {}".format(STA.ifconfig()))

def readTempAndHumi():

    global temp, humi

    try:

        sensor=dht.DHT11(Pin(4))

        sensor.measure()

        temp=sensor.temperature()

        humi=sensor.humidity()

        if (isinstance(temp, float) and isinstance(humi, float)) or (isinstance(temp, int) and isinstance(humi, int)):

          measureResult="{},{}".format(temp, humi)

          return measureResult

        else:

          return ("--")

    except OSError as o:

        print("--")

def Htmlpage():

  html= """

        <html>

    <head>

      <meta charset="utf-8" />

      <meta name="viewport" content="width=device-width, initial-scale=1.0" />

      <style>

        h1  {text-align: center; background-color: orange; margin-right:5px;}

        dl { width: 320px; margin: 12px auto; }

        dt { 

          font-size: 20pt; color: #444; background-color: #ddd;

          margin: 6pt 0; padding: 6pt 12pt;

        }

        dd {

          text-align: right; padding-right: 6pt;

        }

        .num { font-size: 36pt; color: dodgerblue; }

      </style>

      </head>

    <body>

      <p><h1>ESP32 DHT11/12</h1></p>

      <dl>

        <dt>Temp</dt>

        <dd class=num>"""+str(temp)+"""°C</dd>

        <dt>Humi</dt>

        <dd class=num>"""+str(humi)+""" %</dd>

      </dl>

    </body>

    </html>

    """

  return html

  

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind(('', 80))

s.listen(5)

  

while True:

    conn, addr = s.accept()

    print('Got a connection from %s' % str(addr))

    req = conn.recv(1024)

    print('Content = %s' % str(req))

    sensor_reading = readTempAndHumi()

    print(sensor_reading)

    respone = Htmlpage()

    conn.send("http/1.1 200 OK\n")

    conn.send("Content-Type: text/html; charset='utf-8'\n")

    conn.send("Connection: close\n\n")

    conn.sendall(respone)

    conn.close()

解析

**_載入dht,wifi,端口,pin和時間模組_**

import dht

import network, socket

from machine import Pin

from time import sleep

這個部份是設制WiFi的流程

ssid="基地台名稱"

password="基地台密碼"

  
STA=network.WLAN(network.STA_IF)

STA.active(True)

STA.connect(ssid, password)

  

while STA.isconnected()==False:

    pass

print("The connected successful!")

print("IP:  {}".format(STA.ifconfig()))

讀取溫溼度的函式

def readTempAndHumi():

    global temp, humi

    try:

        sensor=dht.DHT11(Pin(4))

        sensor.measure()

        temp=sensor.temperature()

        humi=sensor.humidity()

        if (isinstance(temp, float) and isinstance(humi, float)) or (isinstance(temp, int) and isinstance(humi, int)):

          measureResult="{},{}".format(temp, humi)

          return measureResult

        else:

          return ("--")

    except OSError as o:

        print("--")

網頁前端的布置,記得要讓其讀取時可返回(return)

其中須注意的是讓溫溼度的值可以正顯示要使用“””+str(溫/溼度變數)+”””

def Htmlpage():

  html= """

        <html>

    <head>

      <meta charset="utf-8" />

      <meta name="viewport" content="width=device-width, initial-scale=1.0" />

      <style>

        h1  {text-align: center; background-color: orange; margin-right:5px;}

        dl { width: 320px; margin: 12px auto; }

        dt { 

          font-size: 20pt; color: #444; background-color: #ddd;

          margin: 6pt 0; padding: 6pt 12pt;

        }

        dd {

          text-align: right; padding-right: 6pt;

        }

        .num { font-size: 36pt; color: dodgerblue; }

      </style>

      </head>

    <body>

      <p><h1>ESP32 DHT11/12</h1></p>

      <dl>

        <dt>Temp</dt>

        <dd class=num>"""+str(temp)+"""°C</dd>

        <dt>Humi</dt>

        <dd class=num>"""+str(humi)+""" %</dd>

      </dl>

    </body>

    </html>

    """

  return html

設制監聽套接端口

函式參考-我的micropython函式筆記

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind(('', 80))

s.listen(5)


while True:

    conn, addr = s.accept()

    print('Got a connection from %s' % str(addr))

    req = conn.recv(1024)

    print('Content = %s' % str(req))

    sensor_reading = readTempAndHumi()

    print(sensor_reading)

    respone = Htmlpage()

    conn.send("http/1.1 200 OK\n")

    conn.send("Content-Type: text/html; charset='utf-8'\n")

    conn.send("Connection: close\n\n")

    conn.sendall(respone)

    conn.close()


文章作者: blairan
版權聲明: 本博客所有文章除特別聲明外,均採用 CC BY 4.0 許可協議。轉載請註明來源 blairan !
评论
  目錄