5. Chapter Camera Web Server
In this section, we’ll use ESP32’s video function as an example to study.
5.1. Project 05.1 Camera Web Server
Connect ESP32 using USB and check its IP address through serial monitor. Use web page to access IP address to obtain video and image data.
5.1.1. Component List
ESP32-S3 WROOM x1
|
USB cable x1
|
5.1.2. Circuit
Connect Freenove ESP32-S3 to the computer using the USB cable.
5.1.3. Code
Move the program folder “Freenove ESP32-S3 WROOM Board/Python/Python_Codes” to disk(D) in advance with the path of “D:/Micropython_Codes”.
Since Micropython does not provide firmware including camera module, in this chapter, we will use the camera based on the firmware in lemariva’s Github project, micropython-camera-driver.
Project link: https://github.com/lemariva/micropython-camera-driver
Before starting the project, we need to re-upload the firmware with the camera module via steps below.
Open Thonny, click “run” and select “Select interpreter…”
Select “Micropython (ESP32)”, select “USB Single Serial @ COM28”, and then click the long button under “Firmware”.
Click “Select local MicroPython image ...”.
Choose “esp32s3_camera_st7789_n8r8_1.20.bin”
Select “USB Single Serial @ COM28”
Click “Install”, Wait for completion.
Open “Thonny”, click “This computer” -> “D:” -> “Micropython_Codes” -> “05.1_Camera_WebServer”. Select folder “lib”, right click your mouse to select “Upload to /”, wait for “lib” to be uploaded to ESP32-WROVER and then double click “picoweb_video.py”.
5.1.3.1. 05.1_Camera_WebServer
Before running the program, please modify your router’s name and password in the box shown in the illustration above to make sure that your code can compile and work successfully.
Click “run” to run the code “picoweb_video.py”, then you can see the following content in the shell area.
If your ESP32S3 has been in the process of connecting to router, but the information above has not been printed out, please re-check whether the router name and password have been entered correctly and press the reset key on ESP32S3 to wait for a successful connection prompt.
Open a web browser, enter the IP address printed by the serial monitor in the address bar, and access it.
Taking the Google browser as an example, here’s what the browser prints out after successful access to ESP32S3’s IP.
The effect is shown in the image below.
Please note:
If the shell area prompts an error when you click to run the code, please press the rst button on the ESP32S3, wait for the system reset to complete, and then re-run the code.
The following is the program code.
1# The firmware for this chapter is provided by: https://github.com/cnadler86/micropython-camera-API.
2# Thanks to cnadler86 for the open source contribution.
3
4import network
5import socket
6import time
7from camera import Camera, FrameSize, PixelFormat
8
9# --- Configuration Parameters ---
10SSID = '********' # WiFi SSID
11PASSWORD = '********' # WiFi Password
12CURRENT_FRAME_SIZE = FrameSize.QQVGA # Camera resolution: QQVGA (160x120), QVGA (320x240), etc.
13CAM_PIXEL_FORMAT = PixelFormat.RGB565 # Pixel format: RGB565 is required for this software decoding method
14XCLK_FREQ = 10000000 # Camera clock frequency (10MHz)
15DISPLAY_WIDTH = 320 # Fixed display width on the webpage (CSS pixels)
16DISPLAY_HEIGHT = 240 # Fixed display height on the webpage (CSS pixels)
17
18def get_resolution_dimensions(frame_size):
19 """
20 Returns the actual width and height in pixels based on the FrameSize enum.
21 """
22 if frame_size == FrameSize.QQVGA:
23 return 160, 120
24 elif frame_size == FrameSize.QVGA:
25 return 320, 240
26 elif frame_size == FrameSize.VGA:
27 return 640, 480
28 else:
29 # Default fallback to QQVGA
30 return 160, 120
31
32def connect_wifi(ssid, password):
33 """
34 Connects to the specified WiFi network and returns the local IP address.
35 Blocks execution until connected.
36 """
37 station = network.WLAN(network.STA_IF)
38 station.active(True)
39 station.connect(ssid, password)
40 while not station.isconnected():
41 time.sleep(1)
42 return station.ifconfig()[0]
43
44def init_camera(frame_size, pixel_format, xclk_freq):
45 """
46 Initializes the camera hardware with the specified settings.
47 """
48 cam = Camera(frame_size=frame_size, pixel_format=pixel_format, xclk_freq=xclk_freq, init=False)
49 cam.init()
50 return cam
51
52def generate_html(cam_width, cam_height):
53 """
54 Generates the HTML page with embedded JavaScript.
55 Injects the actual camera resolution into the JS variables.
56 The CSS forces the canvas to display at DISPLAY_WIDTH x DISPLAY_HEIGHT,
57 while the JS handles the actual pixel data decoding.
58 """
59 return f"""<!DOCTYPE html>
60<html>
61<head>
62 <title>ESP32 Camera Stream</title>
63 <style>
64 body {{
65 display: flex;
66 justify-content: center;
67 align-items: center;
68 height: 100vh;
69 margin: 0;
70 background-color: #f0f0f0;
71 }}
72 .video-container {{
73 text-align: center;
74 }}
75 canvas {{
76 /* Force display size to 320x240 regardless of actual resolution */
77 width: {DISPLAY_WIDTH}px;
78 height: {DISPLAY_HEIGHT}px;
79 border: 1px solid #ccc;
80 background-color: #000;
81 image-rendering: auto; /* Smooth scaling */
82 }}
83 </style>
84</head>
85<body>
86 <div class="video-container">
87 <h1>Stream (Actual: {cam_width}x{cam_height}, Display: {DISPLAY_WIDTH}x{DISPLAY_HEIGHT})</h1>
88 <canvas id="videoCanvas"></canvas>
89 <div id="status">Connecting...</div>
90 </div>
91 <script>
92 const canvas = document.getElementById('videoCanvas');
93 const ctx = canvas.getContext('2d');
94 const statusDiv = document.getElementById('status');
95
96 // Actual resolution injected from Python
97 const ACTUAL_WIDTH = {cam_width};
98 const ACTUAL_HEIGHT = {cam_height};
99 const EXPECTED_DATA_LENGTH = ACTUAL_WIDTH * ACTUAL_HEIGHT * 2; // 2 bytes per pixel in RGB565
100
101 function fetchImage() {{
102 fetch('/frame')
103 .then(response => response.arrayBuffer())
104 .then(data => {{
105 if (!data || data.byteLength === 0) {{
106 setTimeout(fetchImage, 100);
107 return;
108 }}
109
110 const uint8Array = new Uint8Array(data);
111 let w = ACTUAL_WIDTH;
112 let h = ACTUAL_HEIGHT;
113
114 // Auto-detect resolution if data length doesn't match expected
115 if (uint8Array.length !== EXPECTED_DATA_LENGTH) {{
116 if (uint8Array.length === 160 * 120 * 2) {{ w = 160; h = 120; }}
117 else if (uint8Array.length === 320 * 240 * 2) {{ w = 320; h = 240; }}
118 else if (uint8Array.length === 640 * 480 * 2) {{ w = 640; h = 480; }}
Import picoweb、utime、camera、gc modules.
1
2import network
3import socket
4import time
Before running the code, please modify the WiFi name and password in the code to ensure that the ESP32S3 can connect to the network.
1
2# --- Configuration Parameters ---
Define the WiFi connection function, set the ESP32S3 to STA mode, and let the ESP32S3 connect to the nearby WiFi. If the connection is successful, the WiFi configuration information of the ESP32S3 will be printed; if the connection fails, the connection timeout will be printed.
1CURRENT_FRAME_SIZE = FrameSize.QQVGA # Camera resolution: QQVGA (160x120), QVGA (320x240), etc.
2CAM_PIXEL_FORMAT = PixelFormat.RGB565 # Pixel format: RGB565 is required for this software decoding method
3XCLK_FREQ = 10000000 # Camera clock frequency (10MHz)
4DISPLAY_WIDTH = 320 # Fixed display width on the webpage (CSS pixels)
5DISPLAY_HEIGHT = 240 # Fixed display height on the webpage (CSS pixels)
6
7def get_resolution_dimensions(frame_size):
8 """
9 Returns the actual width and height in pixels based on the FrameSize enum.
10 """
11 if frame_size == FrameSize.QQVGA:
12 return 160, 120
13 elif frame_size == FrameSize.QVGA:
14 return 320, 240
15 elif frame_size == FrameSize.VGA:
The deinit() is used to disable the configuration of the camera to prevent the previous configuration from interfering with the following configuration.
The init() is used to configure the camera’s pin driver, image data format, resolution and other information. By default, please do not modify this function, otherwise the camera initialization fails and the image cannot be obtained.
1
2def connect_wifi(ssid, password):
3 """
4 Connects to the specified WiFi network and returns the local IP address.
5 Blocks execution until connected.
6 """
7 station = network.WLAN(network.STA_IF)
This function can set the resolution of the camera individually, you can refer to the notes below to select the appropriate resolution size.
1 station.connect(ssid, password)
2 while not station.isconnected():
3 time.sleep(1)
4 return station.ifconfig()[0]
5
6def init_camera(frame_size, pixel_format, xclk_freq):
7 """
The following functions can modify the image information obtained by the camera.
1 """
2 cam = Camera(frame_size=frame_size, pixel_format=pixel_format, xclk_freq=xclk_freq, init=False)
3 cam.init()
4 return cam
5
6def generate_html(cam_width, cam_height):
7 """
8 Generates the HTML page with embedded JavaScript.
9 Injects the actual camera resolution into the JS variables.
10 The CSS forces the canvas to display at DISPLAY_WIDTH x DISPLAY_HEIGHT,
11 while the JS handles the actual pixel data decoding.
12 """
This is the code for a simple web interface, used here as an example.
1<head>
2 <title>ESP32 Camera Stream</title>
3 <style>
4 body {{
5 display: flex;
6 justify-content: center;
7 align-items: center;
8 height: 100vh;
9 margin: 0;
10 background-color: #f0f0f0;
11 }}
12 .video-container {{
Web page response function. When a user visits the webpage “/” built by ESP32S3, ESP32S3 calls this function, allowing the user to observe a display interface in the browser.
1canvas {{
2 /* Force display size to 320x240 regardless of actual resolution */
3 width: {DISPLAY_WIDTH}px;
send_frame() can send the image obtained by ESP32S3 in web page format. When someone visits the webpage “/video” built by the ESP32S3, the video(req, resp) function is used to continuously fetch images and send them to the browser.
1 border: 1px solid #ccc;
2 background-color: #000;
3 image-rendering: auto; /* Smooth scaling */
4 }}
5 </style>
6</head>
7<body>
8 <div class="video-container">
9 <h1>Stream (Actual: {cam_width}x{cam_height}, Display: {DISPLAY_WIDTH}x{DISPLAY_HEIGHT})</h1>
10 <canvas id="videoCanvas"></canvas>
11 <div id="status">Connecting...</div>
12 </div>
13 <script>
14 const canvas = document.getElementById('videoCanvas');
15 const ctx = canvas.getContext('2d');
Create two route decorators and declare their listening strings and corresponding response handlers respectively.
1// Actual resolution injected from Python
2const ACTUAL_WIDTH = {cam_width};
3const ACTUAL_HEIGHT = {cam_height};
4const EXPECTED_DATA_LENGTH = ACTUAL_WIDTH * ACTUAL_HEIGHT * 2; // 2 bytes per pixel in RGB565
5
This is the main part of the program. First initialize the ESP32S3 camera, and then configure WiFi to connect the ESP32S3 to the network. Call the picoweb library, build a webserver, and run it.
1if (!data || data.byteLength === 0) {{
2 setTimeout(fetchImage, 100);
3 return;
4}}
5
6const uint8Array = new Uint8Array(data);
7let w = ACTUAL_WIDTH;
8let h = ACTUAL_HEIGHT;
9
5.1.3.2. Reference
Image resolution |
Sharpness |
Image resolution |
Sharpness |
|---|---|---|---|
FRAMESIZE_96x96 |
96x96 |
FRAMESIZE_HVGA |
480x320 |
FRAMESIZE_QQVGA |
160x120 |
FRAMESIZE_VGA |
640x480 |
FRAMESIZE_QCIF |
176x144 |
FRAMESIZE_SVGA |
800x600 |
FRAMESIZE_HQVGA |
240x176 |
FRAMESIZE_XGA |
1024x768 |
FRAMESIZE_240x240 |
240x240 |
FRAMESIZE_HD |
1280x720 |
FRAMESIZE_QVGA |
320x240 |
FRAMESIZE_SXGA |
1280x1024 |
FRAMESIZE_CIF |
400x296 |
FRAMESIZE_UXGA |
1600x1200 |
We recommend that the resolution not exceed VGA(640x480).

