How to make ESP32 as HTTP webserver using MicroPython ?

In IoT, there are are two components – Embedded device (edge) and application on cloud. Normally server components are hosted in cloud to have better performance as explained in this article. However to increase the edge computing powers, there is also need to host a webserver on edge nodes. This article explains how to run the webserver which uses HTTP protocol. There are two different ways of doing this.

  1. Using picoweb package
  2. Typical Socket programming

Required hardware : ESP32 development kit, Led, DHT 22 sensor,

Required software: Micropython firmware, pycraft IDE

Using Picoweb package

What is picoweb :  It is a “micro” web micro-framework (thus, “pico-framework”) for radically unbloated web applications using radically unbloated Python implementation, MicroPython

ESP32 webserver using micropython
ESP32 webserver using micropython

Features: Asynchronous from the start, Small memory usage, API affinity for similar web frameworks like flask

From REPL prompt of micropython, install picoweb

upip.install(‘picoweb’)
upip.install(‘utemplate’)

Objective : To get the real temperature whenever is request is posted to webserver

Connection: DHT22 is connected to GPIO pin 13 and v3.3 and ground are connected

Approach: Build sensor template which will give the format for presentation layer.
That template is called while making response
yield from picoweb.start_response(resp, content_type = “text/html”)
yield from app.render_template(resp, “sensor.tpl”, (sensor,))
In case of DHCP enabled routers, IP address of ESP32 development kit will be dynamic in nature. So get the ip address and pass it to host name

Code:

Template need to be created and placed inside templates folder

Using Socket programming

Other way of creating webserver is to use sockets and make socket connection,

Objective: Make a connected LED to turn on or off from browser client.

Connection: Connect LED to GPIO 16

Approach: Create socket and listen to the socket.

Code:

Though I personally prefer using picoweb for the benefits of small memory foot print, similarity with flask, depending on the need developers can choose any specific method.

full code is available on git repo

References:

ESP32 MicroPython: HTTP Webserver with Picoweb

https://github.com/pfalcon/picoweb/

http://crufti.com/getting-started-with-iot-development-using-micropython/

16 Comments

Add a Comment

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