ESP32: Simple web server using micropython.

Setup Micropython for ESP32:

ESP32 is a low cost microcontroller that comes with Wi-Fi and Bluetooth connectivity interfaces. We can develop programs for ESP32 using Arduino and ESP-IDF frameworks. We have explained how to develop a simple LED blink program using ESP-IDF in our previous blog https://c2plabs.com/blog/2021/12/31/esp32-led-blink-tutorial-using-esp-idf-freertos-framework/. In addition to these frameworks ESP32 also supports Micropython. ESP32 micropython supports different Microcontroller peripherals like GPIOS, I2C, SPI etc, and also supports Wi-Fi  connectivity and socket programming.  In this blog post we will show how to develop a simple Web Server program using micropython. We are using ESP32 NodeMCU and Ubuntu Linux host for this demo. Thonny python IDE is used for Micropython application development

Micropython firmware for ESP32 NodeMCU is available at https://micropython.org/download/esp32/ for download. Once the the firmware is downloaded, flash to NodeMCU using below commands

epstool.py –chip esp32 –port /dev/ttyUSB0 erase_flash

esptool.py –chip esp32 –port /dev/ttyUSB0 –baud 115200 write_flash -z 0x1000 <downloaded file

Once the Micropython firmware download is completed, launch Thonny IDE and connect to ESP32 board.

Micro-python’s machine library required for using GPIOs, ADC etc, network library is required to establish Wi-Fi connection, python socket library is used to TCP/IP socket communication, import all these required libraries

from machine import Pin, ADC

from utime import sleep_ms

import network

import socket

import esp32

Setup Wi-Fi connection:

ESP32 can be configured as Wi-Fi station or soft AP using micropython. In this example we are configuring esp32 as Wi-Fi station using

station = network.WLAN(network.STA_IF) #network.AP_IF is used to configure as Soft AP.

station.active(True) # This method activates Wi-Fi stack of ESP32

Connect to Wi-Fi access point using credentials station.connect(ssid, password) and check IP print the IP address.

Http Server:

Once ESP32 is connected to Wi-Fi network create TCP/IP socket using python socket library

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM), bind this socket with local IP and port 80 which is the port for http protocol. After the socket is bind to local IP, start listening for new client connections. Start While loop for accepting new client connection and respond with html string which creates a simple web page which updates temperature sensor value connected to ADC3 pin and esp32 on-board hall effect sensor value.

Simple HTML Page:

The html page we are sending contains meta tag for refreshing browser for every 2 seconds.

<meta http-equiv=”refresh” content=”2″> </head>

and Temperature sensor value is read using the read_temp() function which returns temperature value from simple LM35 sensor connected to ADC3 pin.

<p><strong>Temperature in Celcius: “”” + read_temp() + “””</strong>

Along with temperature value, this html page contains hall effect sensor reading

<p><strong>Magnetic field: <strong>””” + str(esp32.hall_sensor()) + “””</strong></p>

We can see browser keep refreshing for every two seconds and sensor values getting displayed on webpage.

Complete working code is give below.



from machine import Pin, ADC
import network
import socket
import esp32
import esp
esp.osdebug(None)

import gc
gc.collect()

ssid = 'myssid'
password = 'wifipasswd'



temp_adc = ADC(Pin(34))
temp_adc.atten(ADC.ATTN_11DB)



def setup_wifi():        
    station = network.WLAN(network.STA_IF)
    station.active(True)
    station.connect(ssid, password)
    while station.isconnected() == False:
        pass
    print('Connection successful')
    print(station.ifconfig())

def http_server():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('', 80))
    sock.listen(5)
    while True:
      client, addr = sock.accept()
      print('Client %s is connected' % str(addr))
      request = client.recv(1024)
      request = str(request)
      response = web_page()
      client.send('HTTP/1.1 200 OK\n')
      client.send('Content-Type: text/html\n')
      client.send('Connection: close\n\n')
      client.sendall(response)
      client.close()

        
def read_temp():
    temp_dig=temp_adc.read()
    print(temp_dig)
    temp_c = str((temp_dig/4096) * 330)
    return temp_c

def web_page():
    html_str="""<html>
                 <head> <title>C2PLabs Demo</title>
                 <meta http-equiv="refresh" content="2"> </head>
                 <body> <h1>C2PLABS Demo</h1>
                 <p><strong>Temperature in Celcius: """ + read_temp() + """</strong></p>
                 <p></P>
                 <p><strong>Magnetic field: <strong>""" + str(esp32.hall_sensor()) + """</strong></p>
                 </body>
                 <style>html{text-align:center}</style>
                 </html>"""
    return html_str

    
def main():
    setup_wifi()
    http_server()
    
    

if __name__ == "__main__":
    main()