IoT Made Easy: ESP-MicroPython-MQTT-ThingSpeak

Running the Local Station Code on ESP Start-upIf you have using Jupyter Notebook to create and test the functions so far, it is to time to have all that were developed so far on a single file script to be executed by our ESP autonomously.Let’s open any text editor and past on it all code (I like to use Geany):from machine import Pinimport time# LEDled = Pin(0, Pin.OUT)# DHTfrom dht import DHT22dht22 = DHT22(Pin(12))def readDht(): dht22.measure() return dht22.temperature(), dht22.humidity()# DS18B20import onewire, ds18x20dat = Pin(2)ds = ds18x20.DS18X20(onewire.OneWire(dat))sensors = ds.scan()def readDs(): ds.convert_temp() time.sleep_ms(750) return round(ds.read_temp(sensors[0]), 1)# LDRfrom machine import ADCadc = ADC(0)def readLdr(): lumPerct = (*(10/86) return round(lumPerct)# Push Buttonbutton = Pin(13, Pin.IN, Pin.PULL_UP)def readBut(): return button.value()# Read all data:def colectData(): temp, hum, = readDht() extTemp = readDs() lum = readLdr() butSts = readBut() return temp, hum, extTemp, lum, butSts# I2C / OLEDfrom machine import I2Cimport ssd1306i2c = I2C(scl=Pin(5), sda=Pin(4))oled = ssd1306.SSD1306_I2C(128, 64, i2c, 0x3c)def displayData(temp, hum, extTemp, lum, butSts): oled.fill(0) oled.text("Temp: " + str(temp) + "oC", 0, 4) oled.text("Hum: " + str(hum) + "%",0, 16) oled.text("ExtTemp: " + str(extTemp) + "oC", 0, 29) oled.text("Lumin: " + str(lum) + "%", 0, 43) oled.text("Button: " + str(butSts), 0, 57) Main functiondef main(): led.on() temp, hum, extTemp, lum, butSts = colectData() displayData(temp, hum, extTemp, lum, butSts)'''—— run main function ——–'''main()Save it, for example as run this code directly on your terminal you will need Ampy.First, on Terminal let’s inform Ampy our Serial port:export AMPY_PORT=/dev/tty.SLAB_USBtoUARTNow, we can see the files that are inside our ESP root directory:ampy lsAs a response, we will get, that is the first file that will run in the system.Now, let’s use Ampy to load our python Script as /, so our script will run just after boot:ampy put /main.pyIf we use the command amp ls now, you will see 2 files inside the ESP: and main.pyResetting your ESP, will make the program (uploaded as / run automatically, displaying the sensor data on display.The above Terminal print screen shows what we have done.With above code, the display will be shown only once, but we can define a loop on main() function, that will show data on every defined time interval (PUB_TIME_SEC), and for example, until we press the button:# loop getting data until button is pressedwhile button.value(): led.on() temp, hum, extTemp, lum, butSts = colectData() displayData(temp, hum, extTemp, lum, butSts) time.sleep(PUB_TIME_SEC)The variable PUB_TIME_SEC must be declared by the time that you want your samples.To enhance more our code, would be good to inform that we will go out from the loop, for that we will define 2 new general functions, one for clear the display and another to blink the LED on a certain number of times.# Clear display :def displayClear(): oled.fill(0) create a blink functiondef blinkLed(num): for i in range(0, num): led.on() sleep(0.5) sleep(0.5)So, we can now, rewrite our main() function:while button.value(): led.on() temp, hum, extTemp, lum, butSts = colectData() displayData(temp, hum, extTemp, lum, butSts) time.sleep(PUB_TIME_SEC) blinkLed(3) displayClear()The final code can be downloaded from my GitHub: and also the Jupyter Notebook used for development of full code: Jupyter Local Data Development.ipynb.7: Connecting the ESP to Local WiFiThe network module is used to configure the WiFi connection..There are two WiFi interfaces, one for the station (when the ESP8266 connects to a router) and one for the access point (for other devices to connect to the ESP8266)..Here, our ESP will be connected to local network via a router..Let’s call the library and define our network credentials:import networkWiFi_SSID = "YOUR SSID"WiFi_PASS = "YOUR PASSWORD"The function below can be used to connect the ESP to your local network:def do_connect(): wlan = network.WLAN(network.STA_IF) if not wlan.isconnected(): print('connecting to network…') wlan.connect(WiFi_SSID, WiFi_SSID) while not wlan.isconnected(): pass print('network config:', wlan.ifconfig())Running the function, you can get as a result the IP address:do_connect()The result will be:network config: (‘’, ‘’, ‘’, ‘’)Were, in my case,, is the ESP IP address.8..The ThingSpeakAt this point, we have learned how to capture data from all sensors, displaying them on our OLED..Now, it is time to see how to send those data to an IoT platform, the“ThingSpeak is an open source Internet of Things (IoT) application to store and retrieve data from things, using REST and MQTT APIs..ThingSpeak enables the creation of sensor logging applications, location tracking applications, and a social network of things with status updates”Let’s begin!First, you must have an account at, follow the instructions to create a Channel and take note of your Channel ID and Write API Key.Above you can see the 5 fields that will be used on our Channel.9..MQTT Protocol and ThingSpeak ConnectionMQTT is a publish/subscribe architecture that is developed primarily to connect bandwidth and power-constrained devices over wireless networks..It is a simple and lightweight protocol that runs over TCP/IP sockets or WebSockets..MQTT over WebSockets can be secured with SSL..The publish/subscribe architecture enables messages to be pushed to the client devices without the device needing to continuously poll the server.The MQTT broker is the central point of communication, and it is in charge of dispatching all messages between the senders and the rightful receivers.. More details

Leave a Reply