0
votes
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)

Apologies for importing the whole script. As it is short, I thought it may be valuable to be able to see all of it. I import time at the top of the script and as far as I can tell, all variables are referenced before they are used.

I would like to import this script as dht_publish and then run dht_publish.run(). However, this gives the following error. This is run on the latest MicroPython binary on an ESP32 dev board.

 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

If I comment out the time.sleep(1) line then the error is flagged on the line before which suggests that the error may be elsewhere in the code but I can't see where. Any help on this would be very much appreciated.

1

1 Answers

0
votes

In case anyone is trying something similar and runs up against the same issue, the problem was that the running variable within the run function was looking up a local variable. Moving the definition of the running variable to the first line after def run(): solved the issue.