016 – ESP32 MicroPython: Web Server | ESP32 Access Point

In this article you will learn to configure ESP32 wifi as Access Point. You will also learn to create a web server hosted on it.
BILL OF MATERIALS:
- ESP32 development board.
- DHT22 (or DHT11 with slight, very small modification in the code).
- Connecting wires.
HARDWARE INSTRUCTION:
- Connect the DHT22 VCC pin to 3.3V pin of ESP32.
- Connect the DHT22 Data pin to D23 pin of ESP32.
- Connect the DHT22 GND pin to GND pin of ESP32.

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. Example # 1, Web Server on ESP32 as Wifi Access Point. The web server is use for controlling the GPIO state of the pins.
# ************************
#
import machine
import time
led = machine.Pin(2,machine.Pin.OUT)
led.off()
# ************************
# Configure the ESP32 wifi
# as Access Point mode.
import network
ssid = 'ESP32-AP-WebServer'
password = '123456789'
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid=ssid, password=password)
while not ap.active():
pass
print('network config:', ap.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 = """<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<center><h2>ESP32 Web Server in MicroPython </h2></center>
<center>
<form>
<button type='submit' name="LED" value='1'> LED ON </button>
<button type='submit' name="LED" 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 OKn')
conn.send('Content-Type: text/htmln')
conn.send('Connection: close\n')
conn.sendall(response)
# Socket close()
conn.close()
2. Example # 2, Display DHT sensor readings through a web server:
# ************************
#
import machine
import time
led = machine.Pin(2,machine.Pin.OUT)
led.off()
# ************************
# Configure the ESP32 wifi
# as Access Point mode.
import network
ssid = 'ESP32-AP-WebServer'
password = '123456789'
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid=ssid, password=password)
while not ap.active():
pass
print('network config:', ap.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
# DHT sensor initializations
import dht
d = dht.DHT22(machine.Pin(23))
# If you will use DHT11, change it to:
# d = dht.DHT11(machine.Pin(23))
# ************************
# Function for creating the
# web page to be displayed
def web_page():
# Get the DHT readings
d.measure()
t = d.temperature()
h = d.humidity()
html_page = """<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="1">
</head>
<body>
<center><h2>ESP32 Web Server in MicroPython </h2></center>
<center><p>Temperature is <strong>""" + str(t) + """ C.</strong>.</p></center>
<center><p>Humidity is <strong>""" + str(h) + """ %.</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("Content %s" % str(request))
# Socket send()
request = str(request)
# Create a socket reply
response = web_page()
conn.send('HTTP/1.1 200 OKn')
conn.send('Content-Type: text/htmln')
conn.send('Connection: close\n')
conn.sendall(response)
# Socket close()
conn.close()
Thank you for your work! I want to ask your advice. I copied your example number one and it doesn't work for me(((. the access Point works, I connect to it, get the IP 192.168.4.2, but the browser doesn't find the page. This is what I see in the terminal:
ets Jun 8 2016 00:22:57
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0018,len:4
load:0x3fff001c,len:5008
ho 0 tail 12 room 4
load:0x40078000,len:10600
ho 0 tail 12 room 4
load:0x40080400,len:5684
entry 0x400806bc
;32mI (538) cpu_start: Pro cpu up.m
;32mI (538) cpu_start: Application information:m
;32mI (539) cpu_start: Compile time: Sep 2 2020 03:00:08m
;32mI (542) cpu_start: ELF file SHA256: 0000000000000000…m
;32mI (548) cpu_start: ESP-IDF: v3.3.2m
;32mI (553) cpu_start: Starting app cpu, entry point is 0x40082f30m
;32mI (0) cpu_start: App cpu up.m
;32mI (563) heap_init: Initializing. RAM available for dynamic allocation:m
;32mI (570) heap_init: At 3FFAFF10 len 000000F0 (0 KiB): DRAMm
;32mI (576) heap_init: At 3FFB6388 len 00001C78 (7 KiB): DRAMm
;32mI (582) heap_init: At 3FFB9A20 len 00004108 (16 KiB): DRAMm
;32mI (588) heap_init: At 3FFBDB5C len 00000004 (0 KiB): DRAMm
;32mI (594) heap_init: At 3FFCA9E8 len 00015618 (85 KiB): DRAMm
;32mI (601) heap_init: At 3FFE0440 len 00003AE0 (14 KiB): D/IRAMm
;32mI (607) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAMm
;32mI (613) heap_init: At 4009DE28 len 000021D8 (8 KiB): IRAMm
;32mI (619) cpu_start: Pro cpu start user codem
;32mI (302) cpu_start: Starting scheduler on PRO CPU.m
;32mI (0) cpu_start: Starting scheduler on APP CPU.m
I (140) wifi:wifi driver task: 3ffd1098, prio:23, stack:3584, core=0
;32mI (585) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSEm
;32mI (585) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSEm
I (625) wifi:wifi firmware version: 44aa95c
I (625) wifi:config NVS flash: enabled
I (625) wifi:config nano formating: disabled
I (625) wifi:Init dynamic tx buffer num: 32
I (625) wifi:Init data frame dynamic rx buffer num: 32
I (635) wifi:Init management frame dynamic rx buffer num: 32
I (635) wifi:Init management short buffer num: 32
I (645) wifi:Init static rx buffer size: 1600
I (645) wifi:Init static rx buffer num: 10
I (645) wifi:Init dynamic rx buffer num: 32
;32mI (755) phy: phy_version: 4180, cb3948e, Sep 12 2019, 16:39:13, 0, 0m
I (755) wifi:mode : softAP (7c:9e:bd:e2:f2:49)
I (765) wifi:Total power save buffer number: 16
I (765) wifi:Init max length of beacon: 752/752
I (765) wifi:Init max length of beacon: 752/752
I (775) wifi:Total power save buffer number: 16
;32mI (775) network: event 14m
;32mI (775) network: event 15m
;32mI (785) network: event 14etwork config: ('192.168.4.1', '255.255.255.0', '192.168.4.1', '0.0.0.0')
[0m
;32mI (795) modsocket: Initializingm
I (1565) wifi:new:<1,0>, old:<1,1>, ap:<1,1>, sta:<255,255>, prof:1
I (1565) wifi:station: 04:92:26:35:69:50 join, AID=1, bgn, 20
;32mI (1565) network: event 16m
;32mI (15165) tcpip_adapter: softAP assign IP to station,IP is: 192.168.4.2m
;32mI (15165) network: event 18m
Hello Sir George,
When I ran the source code: t016_ex02_webserver_ap_socket.py,
I encounter this traceback in my shell below. I'm still debugging it ATM.
***********
Traceback(most recent call last):
File "", line 81, in
File "", line 48, in web_page
File "dht.py", line 17, in measure
OSError:[Errno 110] ETIMEDOUT
*************
Hi, have you tried resetting the board?
Thank You very mutch again.
Marton