015 – ESP32 MicroPython: Web Server | ESP32 Station Mode in MicroPython
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:
- 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 :
ssid = "your_ssid"
password = "your_password"
2. Web server using STA socket:
# ************************
# Web Server in ESP32 using
# web sockets (wifi station)
# Author: George Bantique
# Date: October 28, 2020
# Feel free to modify it
# according to your needs
# ************************
import machine
led = machine.Pin(2,machine.Pin.OUT)
led.off()
# ************************
# Configure the ESP32 wifi
# as STAtion mode.
import network
import wifi_credentials
sta = network.WLAN(network.STA_IF)
if not sta.isconnected():
print('connecting to network...')
sta.active(True)
#sta.connect('your wifi ssid', 'your wifi password')
sta.connect(wifi_credentials.ssid, wifi_credentials.password)
while not sta.isconnected():
pass
print('network config:', sta.ifconfig())
# ************************
# Configure the socket connection
# over TCP/IP
import socket
# AF_INET - use Internet Protocol v4 addresses
# SOCK_STREAM means that it is a TCP socket.
# SOCK_DGRAM means that it is a UDP socket.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('',80)) # specifies that the socket is reachable
# by any address the machine happens to have
s.listen(5) # max of 5 socket connections
# ************************
# Function for creating the
# web page to be displayed
def web_page():
if led.value()==1:
led_state = 'ON'
print('led is ON')
elif led.value()==0:
led_state = 'OFF'
print('led is OFF')
html_page = """
<html>
<head>
<meta content="width=device-width, initial-scale=1" name="viewport"></meta>
</head>
<body>
<center><h2>ESP32 Web Server in MicroPython </h2></center>
<center>
<form>
<button name="LED" type="submit" value="1"> LED ON </button>
<button name="LED" type="submit" value="0"> LED OFF </button>
</form>
</center>
<center><p>LED is now <strong>""" + led_state + """</strong>.</p></center>
</body>
</html>"""
return html_page
while True:
# Socket accept()
conn, addr = s.accept()
print("Got connection from %s" % str(addr))
# Socket receive()
request=conn.recv(1024)
print("")
print("")
print("Content %s" % str(request))
# Socket send()
request = str(request)
led_on = request.find('/?LED=1')
led_off = request.find('/?LED=0')
if led_on == 6:
print('LED ON')
print(str(led_on))
led.value(1)
elif led_off == 6:
print('LED OFF')
print(str(led_off))
led.value(0)
response = web_page()
conn.send('HTTP/1.1 200 OK\n')
conn.send('Content-Type: text/html\n')
conn.send('Connection: close\n\n')
conn.sendall(response)
# Socket close()
conn.close()
3. Web Server with 3 buttons: LED ON, LED OFF, LED Blink:
# ************************
# Web Server in ESP32 using
# web sockets (wifi station)
# Author: George Bantique
# Date: October 28, 2020
# Feel free to modify it
# according to your needs
# ************************
import time
import machine
led = machine.Pin(2,machine.Pin.OUT)
led.off()
# ************************
# Configure the ESP32 wifi
# as STAtion mode.
import network
sta = network.WLAN(network.STA_IF)
if not sta.isconnected():
print('connecting to network...')
sta.active(True)
#sta.connect('your wifi ssid', 'your wifi password')
sta.connect('Tenda_6F1750', 'geoven021110')
while not sta.isconnected():
pass
print('network config:', sta.ifconfig())
# ************************
# Configure the socket connection
# over TCP/IP
import socket
# AF_INET - use Internet Protocol v4 addresses
# SOCK_STREAM means that it is a TCP socket.
# SOCK_DGRAM means that it is a UDP socket.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('',80)) # specifies that the socket is reachable
# by any address the machine happens to have
s.listen(5) # max of 5 socket connections
# ************************
# Function for creating the
# web page to be displayed
def web_page():
if isLedBlinking==True:
led_state = 'Blinking'
print('led is Blinking')
else:
if led.value()==1:
led_state = 'ON'
print('led is ON')
elif led.value()==0:
led_state = 'OFF'
print('led is OFF')
html_page = """
<html>
<head>
<meta content="width=device-width, initial-scale=1" name="viewport"></meta>
</head>
<body>
<center><h2>ESP32 Web Server in MicroPython </h2></center>
<center>
<form>
<button name="LED" type="submit" value="1"> LED ON </button>
<button name="LED" type="submit" value="0"> LED OFF </button>
<button name="LED" type="submit" value="2"> LED BLINK </button>
</form>
</center>
<center><p>LED is now <strong>""" + led_state + """</strong>.</p></center>
</body>
</html>"""
return html_page
tim0 = machine.Timer(0)
def handle_callback(timer):
led.value( not led.value() )
isLedBlinking = False
while True:
# Socket accept()
conn, addr = s.accept()
print("Got connection from %s" % str(addr))
# Socket receive()
request=conn.recv(1024)
print("")
print("")
print("Content %s" % str(request))
# Socket send()
request = str(request)
led_on = request.find('/?LED=1')
led_off = request.find('/?LED=0')
led_blink = request.find('/?LED=2')
if led_on == 6:
print('LED ON')
print(str(led_on))
led.value(1)
if isLedBlinking==True:
tim0.deinit()
isLedBlinking = False
elif led_off == 6:
print('LED OFF')
print(str(led_off))
led.value(0)
if isLedBlinking==True:
tim0.deinit()
isLedBlinking = False
elif led_blink == 6:
print('LED Blinking')
print(str(led_blink))
isLedBlinking = True
tim0.init(period=500, mode=machine.Timer.PERIODIC, callback=handle_callback)
response = web_page()
conn.send('HTTP/1.1 200 OK\n')
conn.send('Content-Type: text/html\n')
conn.send('Connection: close\n\n')
conn.sendall(response)
# Socket close()
conn.close()
Can you explain what the 6 means in this code?
# Socket send()
request = str(request)
led_on = request.find('/?LED=1')
led_off = request.find('/?LED=0')
if led_on == 6:
print('LED ON')
print(str(led_on))
led.value(1)
elif led_off == 6:
print('LED OFF')
print(str(led_off))
led.value(0)
Hi John, try adding print(request) after the request=str(request) then count 0 to 6 and you should found the string LED_ON or LED_OFF. So basically the '6' represents the index in the string.
Thanks for the code and tutorial. Very clear and easy to understand. Access Point tutorial next….