NameError在MicroPython中使用time.sleep

时间:2018-08-24 06:37:18

标签: python micropython esp32

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)行,则会在该行上标记该错误,这表明该错误可能在代码中的其他位置,但我看不到哪里。在这方面的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果有人尝试类似的操作并遇到相同的问题,则问题在于running函数中的run变量正在查找局部变量。在running之后将def run():变量的定义移到第一行解决了该问题。