The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.

Introduction to NodeMCU ESP32 & Micro Python Programming

Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by charles, 2023-01-03 02:54:25

Introduction to NodeMCU ESP32 & Micro Python Programming

Introduction to NodeMCU ESP32 & Micro Python Programming

Keywords: ESP32,micropython

Chapter 5 – NodeMCU ESP32 Using MQTT Protocol 95 while True: try: client.check_msg() if (time.time() - last_message) > message_interval: msg = b'Hello #%d' % counter client.publish(topic_pub, msg) last_message = time.time() counter += 1 except OSError as e: restart_and_reconnect() 14. Save this second script named as ESP32sensor.py into “This Computer”. 15. Upload in your ESP32 Board (make sure you have connected your LED) 16. By using the button in the node-red dashboard, you will get the shell window as shown below: 17. When the ON button is pressed, LED will be turned ON and vice versa.


Chapter 5 – NodeMCU ESP32 Using MQTT Protocol 96 Send Sensor Data from NodeMCU ESP32 to Display on Node-Red Dashboard 1. Join the new node as shown below. 2. Edit MQTT properties in the node as shown below.


Chapter 5 – NodeMCU ESP32 Using MQTT Protocol 97 3. Edit debug node as below.


Chapter 5 – NodeMCU ESP32 Using MQTT Protocol 98 4. Edit the gauge node as below. 5. Edit the chart node as below. 6. Then, DEPLOY the node. 7. Launch the node-red dashboard, and the interface will be shown below.


Chapter 5 – NodeMCU ESP32 Using MQTT Protocol 99 8. Open your Thonny IDE. 9. Save umqttsimple.py (from the last topic script) into “Micropython Device”. 10. Save wifimgr.py (from the last script) into “Micropython Device”. 11. Create a new file script as the given script below. This script is programmed to send data from the DHT22 sensor that reads in NodeMCU ESP32 and sends it to Node-Red. import time import wifimgr from umqttsimple import MQTTClient import ubinascii import machine import micropython import network import esp import dht from machine import Pin esp.osdebug(None) import gc gc.collect() try: import usocket as socket except: import socket # Setup a GPIO Pin for output led = machine.Pin(26, machine.Pin.OUT) fan = machine.Pin(32, machine.Pin.OUT) pin = machine.Pin(2, machine.Pin.OUT) #sensor = dht.DHT22(Pin(14)) sensor = dht.DHT11(Pin(4))


Chapter 5 – NodeMCU ESP32 Using MQTT Protocol 100 wlan = wifimgr.get_connection() if wlan is None: print("Could not initialize the network connection.") while True: pass # you shall not pass :D # Main Code goes here, wlan is a working network.WLAN(STA_IF) instance. print("ESP OK") mqtt_server = 'broker.hivemq.com' #EXAMPLE IP ADDRESS mqtt_server = '10.96.20.133' client_id = ubinascii.hexlify(machine.unique_id()) topic_sub_lamp = b'room/sw/lamp' topic_sub_fan = b'room/sw/fan' topic_pub_temp = b'sensor/dht/temp' topic_pub_hum = b'sensor/dht/hum' last_message = 0 message_interval = 5 counter = 0 def sub_cb(topic, msg): print((topic, msg)) if topic == b'room/sw/lamp' and msg == b"on": led.on() elif topic == b'room/sw/lamp' and msg == b"off": led.off() elif topic == b'room/sw/fan' and msg == b"on": fan.on() elif topic == b'room/sw/fan' and msg == b"off": fan.off() else: led.off() def connect_and_subscribe(): global client_id, mqtt_server, topic_sub_lamp, topic_sub_fan client = MQTTClient(client_id, mqtt_server) client.set_callback(sub_cb) client.connect() pin.on() client.subscribe(topic_sub_lamp) client.subscribe(topic_sub_fan) print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub_lamp)) print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub_fan)) return client def restart_and_reconnect(): print('Failed to connect to MQTT broker. Reconnecting...') time.sleep(10)


Chapter 5 – NodeMCU ESP32 Using MQTT Protocol 101 pin.off() machine.reset() def read_sensor_dht(): try: sensor.measure() temp = sensor.temperature() # uncomment for Fahrenheit #temp = temp * (9/5) + 32.0 hum = sensor.humidity() if (isinstance(temp, float) and isinstance(hum, float)) or (isinstance(temp, int) and isinstance(hum, int)): temp = (b'{0:3.1f},'.format(temp)) hum = (b'{0:3.1f},'.format(hum)) return temp, hum else: return('Invalid sensor readings.') except OSError as e: return('Failed to read sensor.') try: client = connect_and_subscribe() except OSError as e: restart_and_reconnect() try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', 80)) s.listen(5) except OSError as e: machine.reset() while True: try: client.check_msg() if (time.time() - last_message) > message_interval: temp, hum = read_sensor_dht() print(temp) print(hum) client.publish(topic_pub_temp, temp) client.publish(topic_pub_hum, hum) last_message = time.time() counter += 1 except OSError as e: restart_and_reconnect() 12. Connect the DHT22 to your NodeMCU ESP32 Board. 13. “Upload” this script to your NodeMCU ESP32 Board. 14. Test and observe all the results.


Chapter 5 – NodeMCU ESP32 Using MQTT Protocol 102 Problem Based Learning Based on all the steps above and the previous Practical Work 5, use your understanding to get the output in your node-red dashboard and Android or IOS IoT MQTT Panel to control the lamp and fan in your house. The interface in the Node-red dashboard and IOS IoT MQTT Panel is shown below: And


Chapter 5 – NodeMCU ESP32 Using MQTT Protocol 103 Summary In this chapter, IoT Broker has been configured and is ready to receive data from IoT sensor devices. Hopefully, you have successfully published data from IoT sensors devices to monitor and subscribe data to trigger any switch that we want to control.


Chapter 5 – NodeMCU ESP32 Using MQTT Protocol 104 References https://iotdesignpro.com/projects/interface-arduino-with-node-red-to-send-sensor-data-onwebpage https://randomnerdtutorials.com/esp8266-and-node-red-with-mqtt/ DHT11 and MQTT http://pdacontrolen.com/esp8266-public-mqtt-broker-hivemq-node-red/ http://www.steves-internet-guide.com/node-red-admin-basics/ http://www.steves-internet-guide.com/configuring-the-mqtt-publish-node/ http://noderedguide.com/node-red-lecture-4-a-tour-of-the-core-nodes/ https://github.com/hobbyquaker/awesome-mqtt (list of MQTT) https://randomnerdtutorials.com/esp8266-and-node-red-with-mqtt/ https://iotbyhvm.ooo/how-to-connect-esp32-to-mqtt-broker-using-cloudmqtt/ https://dustcloud.atlassian.net/wiki/spaces/ALLDOC/pages/110305930/HiveMQ+integration https://dustcloud.atlassian.net/wiki/spaces/ALLDOC/pages/110305930/HiveMQ+integration#HiveM Qintegration!-PublishTemperaturetoHiveMQ https://thingsboard.io/docs/samples/esp8266/temperature/ (good example) http://www.internetoflego.com/weather-station-dht11-mqtt-node-red-google-chart-oh-my/ (dht11)


Click to View FlipBook Version