Building IoT application using ESP32 and Micropython in 10 Steps

Objective : In this blog we will demonstrate how to build end to end IoT application using ESP32 board and MicroPython as language.

What is required:

ESP32 development board

DHT22 sensor

SSD1306 OLED display

Raspberry Pi

Windows/Linux OS to connect to ESP32 board via serial port

Architecture:

Before explaining architecture, let us understand why we choose these components

Why ESP 32 board: Good specs at decent cost for hackers Dual core , Wifi, 3.3 V logic, Bluetooth

Why Micropython: High level language, Simple and clean, REPL, easy for experimentation and prototyping

This architecture has two components

Publish sensor data (temperature) from Edge on ESP32 using micropython

Subscribe sensor data (temperature) from Raspiberry Pi and display on SSD1306 using python3

Edge side setup (ESP32 setup):

Step 1: Refer earlier blog to setup and get into REPL prompt.

There are three ways to get into this prompt

  1. Using plain serial port communication (cp2102 drivers)
  2.  Using editors like esplorer
  3. Using Rshell
  4.  Using Adafruit Ampy

Step 2:

Connect to Wireless network

import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(True)
sta_if.connect('SSIDname', 'password')
while not sta_if.isconnected():
pass
print('network config:', sta_if.ifconfig())

Step 3: Connect DHT22 with ESP 32

DHT 22 has 4 pins, Pin 1 Vcc on the DHT22 is connected to a 3.3V pin on the ESP32. Pin 2, the DHT-22 data line is connected to GPIO13  Pin 3 is left disconnected and pin 4 ground is connected to a ground on the ESP32.

Step 4: MQTT Publish code

If umqtt is not there , install using this command

upip.install('micropython-umqtt.simple')
from time import sleep
from umqtt.simple import MQTTClient
from machine import Pin
from dht import DHT22
SERVER ='m11.cloudmqtt.com'
CLIENT_ID='ESP32_TH'
PORT=12637
TOPIC=b'temp_humidity'
client=MQTTClient(CLIENT_ID,SERVER,PORT,"cloudmqttusername","cloudmqqttpassword")
client.connect()
sensor=DHT22(Pin(13,Pin.IN,Pin.PULL_UP))
while True:
try:
sensor.measure()
t = sensor.temperature()
h = sensor.humidity()
if isinstance(t, float) and isinstance(h, float):
msg = (b'{0:3.1f},{1:3.1f}'.format(t,h))
client.publish(TOPIC,msg)
print(msg)
else:
print('invalid sensor value')
except OSError:
print ('failed to read sensor')
sleep(4)

Step 5: Verify edge side code

On the serial console, check temperature and humidity values are showing

Pi Side setup

Step 6: Setting up Pi

Install python3 and connect SSD1306

Step 7 : Subscribe code

import paho.mqtt.client as mqtt
def on_connect(client,userdata,flags,rc):
print('connected with result code {0}'.format(rc))
client.subscribe('temp_humidity')
def on_message(client,userdata,msg):
t,h=[float(x) for x in msg.payload.decode("utf-8").split(',')]
print('{0}C {1}%'.format(t,h))
#display_data(t,h)
client=mqtt.Client()
client.username_pw_set('username','password')
client.connect("m11.cloudmqtt.com",port=12637,keepalive=60,bind_address='0.0.0.0')
client.on_connect=on_connect
client.on_message=on_message
#client.subscribe("")
client.loop_start()
input("Press enter to terminate")

Step 8 :Display data code via SSD OLED display

disp = Adafruit_SSD1306.SSD1306_128_32(rst=0)
disp.begin()
FONT_PATH = '/usr/share/fonts/truetype/roboto/RobotoCondensed-Regular.ttf'
FONT = ImageFont.truetype(FONT_PATH, 22)
def display_data(t, h):
image = Image.new('1', (disp.width, disp.height))
draw = ImageDraw.Draw(image)
# Draw temperature / Humidity values.
draw.text((0, 8), '{0}°C'.format(t), font=FONT, fill=255)
draw.text((71, 8), '{0}%'.format(h), font=FONT, fill=255)
# Draw bar charts.
draw.rectangle((0, 0, 50, 8), outline=255, fill=0)
draw.rectangle((71, 0, 121, 8), outline=255, fill=0)
draw.rectangle((0, 0, t / 100.0 * 50, 8), outline=255, fill=255)
draw.rectangle((71, 0, 71 + (h / 100.0 * 50), 8), outline=255, fill=255)
# Send to OLED display.
disp.clear()
disp.image(image)
disp.display()

Verify the reading at SSD console connected with Pi

Step 9 : Also verify the readings from Cloudmqtt console to check the messages are published and subscribed

Step 10 : Take the ESP32 setup with Battery and put it in another place,where temperature and humidity is different. Check SSD console to verify.

References:

rototron.info

crufti.com

https://github.com/gloveboxes/ESP32-MicroPython-BME280-MQTT-Sample

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *