015 - ESP32 MicroPython: Web Server | ESP32 Station Mode in MicroPython

Introduction

In this article, we will learn how to create a web server hosted in ESP32 using MicroPython language for controlling the state of GPIO pin. This can be applied for controlling a relay which is popular in home automation projects.

Bill Of Materials

  1. ESP32 development board with MicroPython firmware.

Video Demonstration

Call To Action

For any concern, write your message in the comment section.

You might also like to support my journey on Youtube by Subscribing. Click this to Subscribe to TechToTinker.

Thank you and have a good days ahead.

See you,

– George Bantique | tech.to.tinker@gmail.com

Source Code

1. wifi_credentials.py :

1ssid = "your_ssid"
2password = "your_password"

2. Web server using STA socket:

  1# ************************
  2# Web Server in ESP32 using
  3# web sockets (wifi station)
  4# Author: George Bantique
  5# Date: October 28, 2020
  6# Feel free to modify it
  7# according to your needs
  8# ************************
  9
 10import machine
 11led = machine.Pin(2,machine.Pin.OUT)
 12led.off()
 13
 14# ************************
 15# Configure the ESP32 wifi
 16# as STAtion mode.
 17import network
 18import wifi_credentials
 19
 20sta = network.WLAN(network.STA_IF)
 21if not sta.isconnected():
 22    print('connecting to network...')
 23    sta.active(True)
 24    #sta.connect('your wifi ssid', 'your wifi password')
 25    sta.connect(wifi_credentials.ssid, wifi_credentials.password)
 26    while not sta.isconnected():
 27        pass
 28print('network config:', sta.ifconfig())
 29
 30# ************************
 31# Configure the socket connection
 32# over TCP/IP
 33import socket
 34
 35# AF_INET - use Internet Protocol v4 addresses
 36# SOCK_STREAM means that it is a TCP socket.
 37# SOCK_DGRAM means that it is a UDP socket.
 38s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 39s.bind(('',80)) # specifies that the socket is reachable 
 40#                 by any address the machine happens to have
 41s.listen(5)     # max of 5 socket connections
 42
 43# ************************
 44# Function for creating the
 45# web page to be displayed
 46def web_page():
 47    if led.value()==1:
 48        led_state = 'ON'
 49        print('led is ON')
 50    elif led.value()==0:
 51        led_state = 'OFF'
 52        print('led is OFF')
 53
 54    html_page = """   
 55      <html>   
 56      <head>   
 57       <meta content="width=device-width, initial-scale=1" name="viewport"></meta>   
 58      </head>   
 59      <body>   
 60        <center><h2>ESP32 Web Server in MicroPython </h2></center>   
 61        <center>   
 62         <form>   
 63          <button name="LED" type="submit" value="1"> LED ON </button>   
 64          <button name="LED" type="submit" value="0"> LED OFF </button>   
 65         </form>   
 66        </center>   
 67        <center><p>LED is now <strong>""" + led_state + """</strong>.</p></center>   
 68      </body>   
 69      </html>"""  
 70    return html_page   
 71
 72while True:
 73    # Socket accept() 
 74    conn, addr = s.accept()
 75    print("Got connection from %s" % str(addr))
 76    
 77    # Socket receive()
 78    request=conn.recv(1024)
 79    print("")
 80    print("")
 81    print("Content %s" % str(request))
 82
 83    # Socket send()
 84    request = str(request)
 85    led_on = request.find('/?LED=1')
 86    led_off = request.find('/?LED=0')
 87    if led_on == 6:
 88        print('LED ON')
 89        print(str(led_on))
 90        led.value(1)
 91    elif led_off == 6:
 92        print('LED OFF')
 93        print(str(led_off))
 94        led.value(0)
 95    response = web_page()
 96    conn.send('HTTP/1.1 200 OK\n')
 97    conn.send('Content-Type: text/html\n')
 98    conn.send('Connection: close\n\n')
 99    conn.sendall(response)
100    
101    # Socket close()
102    conn.close()
  1# ************************
  2# Web Server in ESP32 using
  3# web sockets (wifi station)
  4# Author: George Bantique
  5# Date: October 28, 2020
  6# Feel free to modify it
  7# according to your needs
  8# ************************
  9import time
 10import machine
 11led = machine.Pin(2,machine.Pin.OUT)
 12led.off()
 13
 14# ************************
 15# Configure the ESP32 wifi
 16# as STAtion mode.
 17import network
 18
 19sta = network.WLAN(network.STA_IF)
 20if not sta.isconnected():
 21    print('connecting to network...')
 22    sta.active(True)
 23    #sta.connect('your wifi ssid', 'your wifi password')
 24    sta.connect('Tenda_6F1750', 'geoven021110')
 25    while not sta.isconnected():
 26        pass
 27print('network config:', sta.ifconfig())
 28
 29# ************************
 30# Configure the socket connection
 31# over TCP/IP
 32import socket
 33
 34# AF_INET - use Internet Protocol v4 addresses
 35# SOCK_STREAM means that it is a TCP socket.
 36# SOCK_DGRAM means that it is a UDP socket.
 37s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 38s.bind(('',80)) # specifies that the socket is reachable 
 39#                 by any address the machine happens to have
 40s.listen(5)     # max of 5 socket connections
 41
 42# ************************
 43# Function for creating the
 44# web page to be displayed
 45def web_page():
 46    if isLedBlinking==True:
 47        led_state = 'Blinking'
 48        print('led is Blinking')
 49    else:
 50        if led.value()==1:
 51            led_state = 'ON'
 52            print('led is ON')
 53        elif led.value()==0:
 54            led_state = 'OFF'
 55            print('led is OFF')
 56
 57    html_page = """    
 58    <html>    
 59    <head>    
 60     <meta content="width=device-width, initial-scale=1" name="viewport"></meta>    
 61    </head>    
 62    <body>    
 63     <center><h2>ESP32 Web Server in MicroPython </h2></center>    
 64     <center>    
 65      <form>    
 66      <button name="LED" type="submit" value="1"> LED ON </button>    
 67      <button name="LED" type="submit" value="0"> LED OFF </button>  
 68      <button name="LED" type="submit" value="2"> LED BLINK </button>   
 69      </form>    
 70     </center>    
 71     <center><p>LED is now <strong>""" + led_state + """</strong>.</p></center>    
 72    </body>    
 73    </html>"""  
 74    return html_page   
 75
 76
 77tim0 = machine.Timer(0)
 78def handle_callback(timer):
 79    led.value( not led.value() )
 80isLedBlinking = False
 81
 82while True:
 83    
 84    # Socket accept() 
 85    conn, addr = s.accept()
 86    print("Got connection from %s" % str(addr))
 87    
 88    # Socket receive()
 89    request=conn.recv(1024)
 90    print("")
 91    print("")
 92    print("Content %s" % str(request))
 93
 94    # Socket send()
 95    request = str(request)
 96    led_on = request.find('/?LED=1')
 97    led_off = request.find('/?LED=0')
 98    led_blink = request.find('/?LED=2')
 99    if led_on == 6:
100        print('LED ON')
101        print(str(led_on))
102        led.value(1)
103        if isLedBlinking==True:
104            tim0.deinit()
105            isLedBlinking = False
106        
107    elif led_off == 6:
108        print('LED OFF')
109        print(str(led_off))
110        led.value(0)
111        if isLedBlinking==True:
112            tim0.deinit()
113            isLedBlinking = False
114        
115    elif led_blink == 6:
116        print('LED Blinking')
117        print(str(led_blink))
118        isLedBlinking = True
119        tim0.init(period=500, mode=machine.Timer.PERIODIC, callback=handle_callback)
120        
121    response = web_page()
122    conn.send('HTTP/1.1 200 OK\n')
123    conn.send('Content-Type: text/html\n')
124    conn.send('Connection: close\n\n')
125    conn.sendall(response)
126    
127    # Socket close()
128    conn.close()


Posts in this series



No comments yet!

GitHub-flavored Markdown & a sane subset of HTML is supported.