import time
from umqtt.simple import MQTTClient
from machine import Pin
from dht import DHT22
SERVER = 'X.X.X.X' # MQTT Server Address (Change to the IP address of your Pi)
CLIENT_ID = 'ESP32_DHT22_Sensor'
TOPIC = b'temp_humidity'
running = True
client = MQTTClient(CLIENT_ID, SERVER)
client.connect() # Connect to MQTT broker
sensor = DHT22(Pin(15, Pin.IN, Pin.PULL_UP)) # DHT-22 on GPIO 15 (input with internal pull-up resistor)
def run():
while running:
try:
sensor.measure() # Poll sensor
t = sensor.temperature()
h = sensor.humidity()
tm = time.localtime(time.time())
if isinstance(t, float) and isinstance(h, float) and tm[0] > 2000: # Confirm sensor results$
msg = (b'{0:n},{1:n},{2:n},{3:n},{4:n},{5:3.1f},{6:3.1f}'.format(tm[0], tm[1], tm[2]$
client.publish(TOPIC, msg, retain=True) # Publish sensor data to MQTT topic
print(str(msg))
print('Sent to ' + SERVER + ' as ' + CLIENT_ID + '. Exiting.')
running = False
else:
print('Invalid sensor readings.')
except OSError:
print('Failed to read sensor.')
time.sleep(1)
抱歉导入整个脚本。由于它很短,我认为能够看到所有这些可能很有价值。我在脚本顶部导入时间,据我所知,所有变量在使用之前都会被引用。
我想将此脚本作为 dht_publish 导入,然后运行 dht_publish.run()。但是,这会产生以下错误。这是在 ESP32 开发板上的最新 MicroPython 二进制文件上运行的。
Traceback (most recent call last):
File <stdin>, line 1, in <module>
File dht_publish.py, line 33, in run
NameError: local variable referenced before assignment
如果我注释掉 time.sleep(1) 行,则错误会在之前的行上标记,这表明错误可能在代码中的其他地方,但我看不到在哪里。对此的任何帮助将不胜感激。