100% found this document useful (2 votes)
184 views

C Tutorial

The document introduces the ESP32-S3 development board made by Freenove, providing an overview of its features and capabilities. It outlines the components included in development kits for learning programming and electronics projects using ESP32-S3. The document is a tutorial that will guide users through projects of increasing complexity involving LEDs, serial communication, Bluetooth, WiFi, TCP/IP, cameras, and more.

Uploaded by

songpengyuan123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
184 views

C Tutorial

The document introduces the ESP32-S3 development board made by Freenove, providing an overview of its features and capabilities. It outlines the components included in development kits for learning programming and electronics projects using ESP32-S3. The document is a tutorial that will guide users through projects of increasing complexity involving LEDs, serial communication, Bluetooth, WiFi, TCP/IP, cameras, and more.

Uploaded by

songpengyuan123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 142

█ www.freenove.

com

Important Information
Thank you for choosing Freenove products!

Getting Started

First, please read the Start Here.pdf document in the unzipped folder you created.
If you have not yet downloaded the zip file, associated with this kit, please do so now and unzip it.

Get Support and Offer Input

Freenove provides free and responsive product and technical support, including but not limited to:
 Product quality issues
 Product use and build issues
 Questions regarding the technology employed in our products for learning and education
 Your input and opinions are always welcome
 We also encourage your ideas and suggestions for new products and product improvements
For any of the above, you may send us an email to:

support@freenove.com
Safety and Precautions

Please follow the following safety precautions when using or storing this product:
 Keep this product out of the reach of children under 6 years old.
 This product should be used only when there is adult supervision present as young children lack
necessary judgment regarding safety and the consequences of product misuse.
 This product contains small parts and parts, which are sharp. This product contains electrically conductive
parts. Use caution with electrically conductive parts near or around power supplies, batteries and
powered (live) circuits.
 When the product is turned ON, activated or tested, some parts will move or rotate. To avoid injuries
to hands and fingers keep them away from any moving parts!
 It is possible that an improperly connected or shorted circuit may cause overheating. Should this happen,
immediately disconnect the power supply or remove the batteries and do not touch anything until
it cools down! When everything is safe and cool, review the product tutorial to identify the cause.
 Only operate the product in accordance with the instructions and guidelines of this tutorial, otherwise
parts may be damaged or you could be injured.
 Store the product in a cool dry place and avoid exposing the product to direct sunlight.
 After use, always turn the power OFF and remove or unplug the batteries before storing.

Any concerns?  support@freenove.com


www.freenove.com █

About Freenove

Freenove provides open source electronic products and services worldwide.

Freenove is committed to assist customers in their education of robotics, programming and electronic circuits
so that they may transform their creative ideas into prototypes and new and innovative products. To this end,
our services include but are not limited to:

 Educational and Entertaining Project Kits for Robots, Smart Cars and Drones
 Educational Kits to Learn Robotic Software Systems for Arduino, Raspberry Pi and micro: bit
 Electronic Component Assortments, Electronic Modules and Specialized Tools
 Product Development and Customization Services

You can find more about Freenove and get our latest news and updates through our website:

http://www.freenove.com

sale@freenove.com

Copyright

All the files, materials and instructional guides provided are released under Creative Commons Attribution-
NonCommercial-ShareAlike 3.0 Unported License. A copy of this license can be found in the folder containing
the Tutorial and software files associated with this product.

This means you can use these resource in your own derived works, in part or completely but NOT for the
intent or purpose of commercial use.

Freenove brand and logo are copyright of Freenove Creative Technology Co., Ltd. and cannot be used without
written permission.

TM

Any concerns?  support@freenove.com


█ www.freenove.com Preface 1

Contents

Important Information ...................................................... 1


Contents................................................................................. 1
Preface .................................................................................... 3
ESP32-S3 WROOM .................................................................................................................................................................. 4
CH343 (Importance) ................................................................................................................................................................. 6
Programming Software ......................................................................................................................................................... 18
Environment Configuration ................................................................................................................................................. 21
Notes for GPIO......................................................................................................................................................................... 24

Chapter 1 LED ................................................................... 27


Project 1.1 Blink ....................................................................................................................................................................... 27

Chapter 2 Serial Communication................................ 36


Project 2.1 Serial Print............................................................................................................................................................ 36
Project 2.2 Serial Read and Write ...................................................................................................................................... 40

Chapter 3 Bluetooth........................................................ 42
Project 3.1 Bluetooth Low Energy Data Passthrough ................................................................................................. 42

Chapter 4 Read and Write the SDcard ..................... 54


Project 4.1 SDMMC Test ....................................................................................................................................................... 54

Chapter 5 WiFi Working Modes.................................. 66


Project 5.1 Station mode ...................................................................................................................................................... 66
Project 5.2 AP mode .............................................................................................................................................................. 71
Project 5.3 AP+Station mode ............................................................................................................................................. 76

Chapter 6 TCP/IP.............................................................. 80
Project 6.1 As Client ............................................................................................................................................................... 80
Project 6.2 As Server .............................................................................................................................................................. 92

Chapter 7 Camera Web Server ................................... 98


Project 7.1 Camera Web Server ......................................................................................................................................... 98
Project 7.2 Video Web Server .......................................................................................................................................... 107
Project 7.3 Camera and SDcard ...................................................................................................................................... 113

Chapter 8 Camera Tcp Server.................................... 122


Project 8.1 Camera Tcp Server ........................................................................................................................................ 122
Any concerns?  support@freenove.com
2 Preface www.freenove.com █

What’s next? .................................................................... 140


End of the Tutorial ......................................................... 140

Any concerns?  support@freenove.com


█ www.freenove.com Preface 3

Preface
ESP32-S3 is a micro control unit with integrated Wi-Fi launched by Espressif, which features strong properties
and integrates rich peripherals. It can be designed and studied as an ordinary Single Chip Micyoco(SCM) chip,
or connected to the Internet and used as an Internet of Things device.

ESP32-S3 can be developed using the Arduino platform, which will definitely make it easier for people who
have learned arduino to master. Moreover, the code of ESP32-S3 is completely open-source, so beginners
can quickly learn how to develop and design IOT smart household products including smart curtains, fans,
lamps and clocks.

Generally, ESP32-S3 projects consist of code and circuits. Don't worry even if you've never learned code and
circuits, because we will gradually introduce the basic knowledge of C programming language and electronic
circuits, from easy to difficult. Our products contain all the electronic components and modules needed to
complete these projects. It's especially suitable for beginners.

We divide each project into four parts, namely Component List, Component Knowledge, Circuit and Code.
Component List helps you to prepare material for the experiment more quickly. Component Knowledge allows
you to quickly understand new electronic modules or components, while Circuit helps you understand the
operating principle of the circuit. And Code allows you to easily master the use of SEP32 and accessory kit.
After finishing all the projects in this tutorial, you can also use these components and modules to make
products such as smart household, smart cars and robots to transform your creative ideas into prototypes
and new and innovative products.

In addition, if you have any difficulties or questions with this tutorial or toolkit, feel free to ask for our quick
and free technical support through support@freenove.com

Any concerns?  support@freenove.com


4 Preface www.freenove.com █

ESP32-S3 WROOM

ESP32-S3-WROOM-1 has launched a total of two antenna packages, PCB on-board antenna and IPEX
antenna respectively. The PCB on-board antenna is an integrated antenna in the chip module itself, so it is
convenient to carry and design. The IPEX antenna is a metal antenna derived from the integrated antenna of
the chip module itself, which is used to enhance the signal of the module.
PCB on-board antenna IPEX antenna

In this tutorial, the ESP32-S3 WROOM is designed based on the PCB on-board antenna-packaged ESP32-
S3-WROOM-1 module.
ESP32-S3 WROOM

Any concerns?  support@freenove.com


█ www.freenove.com Preface 5

The hardware interfaces of ESP32-S3 WROOM are distributed as follows:

Compare the left and right images. We've boxed off the resources on the ESP32-S3 WROOM in different
colors to facilitate your understanding of the ESP32-S3 WROOM.
Box color Corresponding resources introduction
GPIO pin

LED indicator

Camera interface

Reset button, Boot mode selection button

USB port

For more information, please visit: https://www.espressif.com.cn/sites/default/files/documentation/esp32-


s3-wroom-1_wroom-1u_datasheet_en.pdf.

Any concerns?  support@freenove.com


6 Preface www.freenove.com █

CH343 (Importance)

ESP32-S3 WROOM uses CH343 to download codes. So before using it, we need to install CH343 driver in our
computers.

Windows

Check whether CH343 has been installed


1. Connect your computer and ESP32-S3 WROOM with a USB cable.

2. Turn to the main interface of your computer, select “This PC” and right-click to select “Manage”.

Any concerns?  support@freenove.com


█ www.freenove.com Preface 7

3. Click “Device Manager”. If your computer has installed CH343, you can see“USB-Enhances-SERIAL
CH343 (COMx)”. And you can click here to move to the next step.

CH343 Port

Installing CH343
1. First, download CH343 driver, click http://www.wch-ic.com/search?t=all&q=ch343 to download the
appropriate one based on your operating system.

Any concerns?  support@freenove.com


8 Preface www.freenove.com █

Windows

MAC

If you would not like to download the installation package, you can open
“Freenove_ESP32_S3_WROVER_Board/CH343”, we have prepared the installation package.

Any concerns?  support@freenove.com


█ www.freenove.com Preface 9

2. Open the folder “Freenove_ESP32_S3_WROVER_Board/CH343/Windows/”

3. Double click “CH343SER.EXE”.

Any concerns?  support@freenove.com


10 Preface www.freenove.com █

4. Click “INSTALL” and wait for the installation to complete.

5. Install successfully. Close all interfaces.

Any concerns?  support@freenove.com


█ www.freenove.com Preface 11

6. When ESP32-S3 WROOM is connected to computer, select “This PC”, right-click to select “Manage” and
click “Device Manager” in the newly pop-up dialog box, and you can see the following interface.

7. So far, CH343 has been installed successfully. Close all dialog boxes.

Any concerns?  support@freenove.com


12 Preface www.freenove.com █

MAC

First, download CH343 driver, click http://www.wch-ic.com/search?t=all&q=ch343 to download the


appropriate one based on your operating system.

Windows

MAC

If you would not like to download the installation package, you can open
“Freenove_ESP32_S3_WROVER_Board/CH343”, we have prepared the installation package.
Second, open the folder “Freenove_ESP32_S3_WROVER_Board/CH343/MAC/”

Any concerns?  support@freenove.com


█ www.freenove.com Preface 13

Run it.

Third, click Continue.

Fourth, click Install.

Any concerns?  support@freenove.com


14 Preface www.freenove.com █

Any concerns?  support@freenove.com


█ www.freenove.com Preface 15

Then, waiting Finsh.

Finally, restart your PC.

Any concerns?  support@freenove.com


16 Preface www.freenove.com █

Any concerns?  support@freenove.com


█ www.freenove.com Preface 17

If you still haven't installed the CH340 by following the steps above, you can view readme.pdf to install it.

ReadMe

Any concerns?  support@freenove.com


18 Preface www.freenove.com █

Programming Software

Arduino Software (IDE) is used to write and upload the code for Arduino Board.
First, install Arduino Software (IDE): visit https://www.arduino.cc, click "Download" to enter the download page.

Select and download corresponding installer according to your operating system. If you are a windows user,
please select the "Windows Installer" to download to install the driver correctly.

After the download completes, run the installer. For Windows users, there may pop up an installation dialog
box of driver during the installation process. When it popes up, please allow the installation.

After installation is complete, an Arduino Software shortcut will be generated in the desktop. Run the Arduino
Software.

Any concerns?  support@freenove.com


█ www.freenove.com Preface 19

The interface of Arduino Software is as follows:

Menus

Toolbar

Text editor

Message
area

Console

Configured board
and serial port

Any concerns?  support@freenove.com


20 Preface www.freenove.com █

Programs written with Arduino Software (IDE) are called sketches. These sketches are written in the text
editor and saved with the file extension.ino. The editor has features for cutting/pasting and
searching/replacing text. The message area gives feedback while saving and exporting and also displays
errors. The console displays text output by the Arduino Software (IDE), including complete error messages
and other information. The bottom right-hand corner of the window displays the configured board and
serial port. The toolbar buttons allow you to verify and upload programs, create, open, and save sketches,
and open the serial monitor.

Verify
Check your code for compile errors .
Upload
Compile your code and upload them to the configured board.
Debug
Debug code running on the board. (Some development boards do not
support this function)
Development board selection
Configure the support package and upload port of the development
board.
Serial Plotter
Receive serial port data and plot it in a discounted graph.
Serial Monitor
Open the serial monitor.

Additional commands are found within the five menus: File, Edit, Sketch, Tools, Help. The menus are context
sensitive, which means only those items relevant to the work currently being carried out are available.

Any concerns?  support@freenove.com


█ www.freenove.com Preface 21

Environment Configuration

First, open the software platform arduino, and then click File in Menus and select Preferences.

Second, click on the symbol behind "Additional Boards Manager URLs"

Any concerns?  support@freenove.com


22 Preface www.freenove.com █

Third, fill in https://raw.githubusercontent.com/espressif/arduino-esp32/gh-


pages/package_esp32_index.json in the new window, click OK, and click OK on the Preferences window
again.

Fourth, click "Boards Manager". Enter “esp32” in Boards manager and select 2.0.5,Then click “INSTALL”.

Any concerns?  support@freenove.com


█ www.freenove.com Preface 23

Arduinowill download these files automaticly. Wait for the installation to complete.

When finishing installation, click Tools in the Menus again and select Board: "Arduino Uno", and then you
can see information of ESP32. click "ESP32-S3 Dev Module" so that the ESP32-S3 programming
development environment is configured.

Any concerns?  support@freenove.com


24 Preface www.freenove.com █

Notes for GPIO

Strapping Pin

There are four Strapping pins for ESP32-S3:GPIO0、GPIO45、GPIO46、GPIO3。


With the release of the chip's system reset (power-on reset, RTC watchdog reset, undervoltage reset), the
strapping pins sample the level and store it in the latch as "0" or "1" ", and keep it until the chip is powered
off or turned off.
Each Strapping pin is connecting to internal pull-up/pull-down. Connecting to high-impedance external
circuit or without an external connection, a strapping pin's default value of input level will be determined by
internal weak pull-up/pull-down. To change the value of the Strapping, users can apply an external pull-
down/pull-up resistor, or use the GPIO of the host MCU to control the level of the strapping pin when the
ESP32-S3’s power on reset is released.
When releasing the reset, the strapping pin has the same function as a normal pin.
The followings are default configurations of these four strapping pins at power-on and their functions under
the corresponding configuration.

If you have any difficulties or questions with this tutorial or toolkit, feel free to ask for our quick and free
technical support through support@freenove.com at any time.
or check: https://www.espressif.com/sites/default/files/documentation/esp32-s3-wroom-1_wroom-
1u_datasheet_en.pdf

Any concerns?  support@freenove.com


█ www.freenove.com Preface 25

PSRAM Pin

The module on the ESP32-S3-WROOM board uses the ESP32-S3R8 chip with 8MB of external Flash. When
we use the OPI PSRAM, please note that the GPIO35-GPIO37 on the ESP32-S3-WROOM board will not be
available for other purposes. When OPI PSRAM is not used, GPIO35-GPIO37 on the board can be used as
normal GPIO.

SDcard Pin

An SDcard slot is integrated on the back of the ESP32-S3-WROOM board. We can use GPIO38-GPIO40 of
ESP32-S3-WROOM to drive SD card.
The SDcard of ESP32-S3-WROOM uses SDMMC, a 1-bit bus driving method, which has been integrated in
the Arduino IDE, and we can call the "SD_MMC.h" library to drive it. For details, see the SDcard chapter in this
tutorial.

USB Pin

In Micropython, GPIO19 and GPIO20 are used for the USB function of ESP32S3, so they cannot be used as
other functions!

Any concerns?  support@freenove.com


26 Preface www.freenove.com █

Cam Pin

When using the camera of our ESP32-S3 WROOM, please check the pins of it. Pins with underlined
numbers are used by the camera function, if you want to use other functions besides it, please avoid using
them.

CAM_Pin GPIO_pin
SIOD GPIO4
SIOC GPIO5
CSI_VYSNC GPIO6
CSI_HREF GPIO7
CSI_Y9 GPIO16
XCLK GPIO15
CSI_Y8 GPIO17
CSI_Y7 GPIO18
CSI_PCLK GPIO13
CSI_Y6 GPIO12
CSI_Y2 GPIO11
CSI_Y5 GPIO10
CSI_Y3 GPIO9
CSI_Y4 GPIO8
If you have any questions about the information of GPIO, you can click here to go back to ESP32-S3
WROOM to view specific information about GPIO.
or check: https://www.espressif.com/sites/default/files/documentation/esp32-s3_datasheet_en.pdf.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 1 LED 27

Chapter 1 LED
This chapter is the Start Point in the journey to build and explore ESP32-S3 WROOM electronic projects. We
will start with simple “Blink” project.

Project 1.1 Blink

In this project, we will use ESP32-S3 WROOM to control blinking a common LED.

Component List

ESP32-S3 WROOM x1 USB cable x1

Power
ESP32-S3 WROOM needs 5v power supply. In this tutorial, we need connect ESP32-S3 WROOM to computer
via USB cable to power it and program it. We can also use other 5v power source to power it.

In the following projects, we only use USB cable to power ESP32-S3 WROOM by default.
In the whole tutorial, we don’t use T extension to power ESP32-S3 WROOM. So 5V and 3.3V (includeing EXT
3.3V) on the extension board are provided by ESP32-S3 WROOM.
We can also use DC jack of extension board to power ESP32-S3 WROOM. In this way, 5v and EXT 3.3v on
extension board are provided by external power resource.

Any concerns?  support@freenove.com


28 Chapter 1 LED www.freenove.com █

Sketch

According to the circuit, when the GPIO2 of ESP32-S3 WROOM output level is high, the LED turns ON.
Conversely, when the GPIO2 ESP32-S3 WROOM output level is low, the LED turns OFF. Therefore, we can let
GPIO2 circularly output high and low level to make the LED blink.
Upload the following Sketch:
Freenove_ESP32_S3_WROVER_Board\Sketches\Sketch_01.1_Blink.
Next we will introduce two ways to upload code to ESP32-S3 WROOM.
Option 1:
Connect ESP32-S3 WROOM to computer.

Open Arduino IDE 2.0.0. Click Tools->Upload Mode. Select UART0 / Hardware CDC.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 1 LED 29

Before uploading the code, click "Tools", "Board" and select "ESP32S3 Dev Module".

Select the serial port.


Note that the computer port number of each user may be different. Please select the correct serial
port according to your computer. Taking the window system as an example, my computer
recognizes that the communication interface of the ESP32-S3-WROOM is COM3, so I select COM3.

Any concerns?  support@freenove.com


30 Chapter 1 LED www.freenove.com █

Note: For macOS users, if the uploading fails, please set the baud rate to 115200 before clicking
“Upload Using Programmer”.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 1 LED 31

Click the Upload button and it will compile and upload the Sketch to the ESP32-S3-WROOM.

Wait for the Sketch upload to complete, and observe the ESP32-S3-WROOM. You can see that the blue
LED (IO2) on the board flashes cyclically.

If you have any concerns, please contact us via: support@freenove.com.

Any concerns?  support@freenove.com


32 Chapter 1 LED www.freenove.com █

Option 2:
Connect ESP32-S3 WROOM to computer.

Open Arduino IDE 2.0.0. Click Tools->Upload Mode. Select USB-OTG CDC(TinyUSB).

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 1 LED 33

Select the serial port.


Note that the computer port number of each user may be different. Please select the correct serial
port according to your computer. Taking the window system as an example, my computer
recognizes that the communication interface of the ESP32-S3-WROOM is COM25, so I select
COM25.

Click the Upload button and it will compile and upload the Sketch to the ESP32-S3-WROOM.

Wait for the Sketch upload to complete, and observe the ESP32-S3-WROOM. You can see that the blue

Any concerns?  support@freenove.com


34 Chapter 1 LED www.freenove.com █

LED (IO2) on the board flashes cyclically.

Sketch_01.1_Blink
The following is the program code:
1 #define LED_BUILTIN 2
2 // the setup function runs once when you press reset or power the board
3 void setup() {
4 // initialize digital pin LED_BUILTIN as an output.
5 pinMode(LED_BUILTIN, OUTPUT);
6 }
7
8 // the loop function runs over and over again forever
9 void loop() {
10 digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
11 delay(1000); // wait for a second
12 digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
13 delay(1000); // wait for a second
14 }

The Arduino IDE code usually contains two basic functions: void setup() and void loop().
After the board is reset, the setup() function will be executed firstly, and then the loop() function.
setup() function is generally used to write code to initialize the hardware. And loop() function is used to write
code to achieve certain functions. loop() function is executed repeatedly. When the execution reaches the end
of loop(), it will jump to the beginning of loop() to run again.

Reset 1 // the setup function runs once when you press reset or power the board
2 void setup() {
… …
5 }
6
7 // the loop function runs over and over again forever

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 1 LED 35

8 void loop() {
… …
13 }

Reset
Reset operation will lead the code to be executed from the beginning. Switching on the power, finishing
uploading the code and pressing the reset button will trigger reset operation.
In the circuit, ESP32-S3 WROOM's GPIO2 is connected to the LED, so the LED pin is defined as 2.
1 #define LED_BUILTIN 2
This means that after this line of code, all LED_BUILTIN will be treated as 2.
In the setup () function, first, we set the LED_BUILTIN as output mode, which can make the port output high
level or low level.
4 // initialize digital pin LED_BUILTIN as an output.
5 pinMode(LED_BUILTIN, OUTPUT);
Then, in the loop () function, set the LED_BUILTIN to output high level to make LED light up.
10 digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
Wait for 1000ms, that is 1s. Delay () function is used to make control board wait for a moment before executing
the next statement. The parameter indicates the number of milliseconds to wait for.
11 delay(1000); // wait for a second
Then set the LED_BUILTIN to output low level, and LED light off. One second later, the execution of loop ()
function will be completed.
12 digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
13 delay(1000); // wait for a second
The loop() function is constantly being executed, so LED will keep blinking.

Reference
void pinMode(int pin, int mode);
Configures the specified pin to behave either as an input or an output.
Parameters
pin: the pin number to set the mode of.
mode: INPUT, OUTPUT, INPUT_PULLDOWM, or INPUT_PULLUP.
void digitalWrite (int pin, int value);
Writes the value HIGH or LOW (1 or 0) to the given pin which must have been previously set as an output.
For more related functions, please refer to https://www.arduino.cc/reference/en/

Any concerns?  support@freenove.com


36 Chapter 2 Serial Communication www.freenove.com █

Chapter 2 Serial Communication


Serial Communication is a means of communication between different devices/devices. This section describes
ESP32-S3’s Serial Communication.

Project 2.1 Serial Print

This project uses ESP32-S3’s serial communicator to send data to the computer and print it on the serial
monitor.

Component List

ESP32-S3 WROOM x1 GPIO Extension Board x1

Micro USB Wire x1

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 2 Serial Communication 37

Related knowledge

Serial communication
Serial communication generally refers to the Universal Asynchronous Receiver/Transmitter (UART), which is
commonly used in electronic circuit communication. It has two communication lines, one is responsible for
sending data (TX line) and the other for receiving data (RX line). The serial communication connections of
two devices is as follows:
Device 1 Device 2

RX RX
TX TX

Before serial communication starts, the baud rate of both sides must be the same. Communication between
devices can work only if the same baud rate is used. The baud rates commonly used is 9600 and 115200.

Serial port on ESP32-S3


Freenove ESP32-S3 has integrated USB to serial transfer, so it could communicate with computer connecting
to USB cable.
ESP32-S3 USB to Serial Computer

UART
UART COM
USB

Arduino Software also uploads code to Freenove ESP32-S3 through the serial connection.
Your computer identifies serial devices connecting to it as COMx. We can use the Serial Monitor window of
Arduino Software to communicate with Freenove ESP32-S3, connect Freenove ESP32-S3 to computer
through the USB cable, choose the correct device, and then click the Serial Monitor icon to open the Serial
Monitor window.

Interface of serial monitor window is as follows. If you can't open it, make sure Freenove ESP32-S3 has been
connected to the computer, and choose the right serial port in the menu bar "Tools".

Title bar

Data-
sending
Data- area
receiving
area

Any concerns?  support@freenove.com

Configure
38 Chapter 2 Serial Communication www.freenove.com █

Circuit

Connect Freenove ESP32-S3 to the computer with USB cable.

Sketch

Sketch_02.1_SerialPrinter

Download the code to ESP32-S3 WROOM, open the serial port monitor, set the baud rate to 115200, and
press the reset button. As shown in the following figure:

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 2 Serial Communication 39

As shown in the image above, "ESP32-S3 initialization completed! " The previous is the printing message
when the system is started. The user program is then printed at a baud rate of 115200.

The following is the program code:


1 void setup() {
2 Serial.begin(115200);
3 Serial.println("ESP32S3 initialization completed! ");
4 }
5
6 void loop() {
7 Serial.printf("Running time : %.1f s\n", millis() / 1000.0f);
8 delay(1000);
9 }

Reference
void begin(unsigned long baud, uint32_t config=SERIAL_8N1, int8_t rxPin=-1,
int8_t txPin=-1, bool invert=false, unsigned long timeout_ms = 20000UL);
Initializes the serial port. Parameter baud is baud rate, other parameters generally use the default value.
size_t println( arg );
Print to the serial port and wrap. The parameter arg can be a number, a character, a string, an array of
characters, etc.
size_t printf(const char * format, ...) __attribute__ ((format (printf, 2, 3)));
Print formatted content to the serial port in the same way as print in standard C.
unsigned long millis();
Returns the number of milliseconds since the current system was booted.

Any concerns?  support@freenove.com


40 Chapter 2 Serial Communication www.freenove.com █

Project 2.2 Serial Read and Write

From last section, we use serial port on Freenove ESP32-S3 to send data to a computer, now we will use that
to receive data from computer.

Component and circuit are the same as in the previous project.

Sketch

Sketch_02.2_SerialRW

Download the code to ESP32-S3 WROOM, open the serial monitor, and set the top right corner to Newline,
115200. As shown in the following figure:

Then type characters like 'ABCDEFG' into the data sent at the top, and press Ctrl+Enter to send the
message.

Input

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 2 Serial Communication 41

The following is the program code:


1 String inputString = ""; //a String to hold incoming data
2 bool stringComplete = false; // whether the string is complete
3
4 void setup() {
5 Serial.begin(115200);
6 Serial.println(String("\nESP32S3 initialization completed! \r\n")
7 + String("Please input some characters,\r\n")
8 + String("select \"Newline\" below and Ctrl + Enter to send message to
ESP32S3. \r\n"));
9 }
10
11 void loop() {
12 if (Serial.available()) { // judge whether data has been received
13 char inChar = Serial.read(); // read one character
14 inputString += inChar;
15 if (inChar == '\n') {
16 stringComplete = true;
17 }
18 }
19 if (stringComplete) {
20 Serial.printf("inputString: %s \n", inputString);
21 inputString = "";
22 stringComplete = false;
23 }
24 }

In loop(), determine whether the serial port has data, if so, read and save the data, and if the newline
character is read, print out all the data that has been read.

Reference
String();
Constructs an instance of the String class.
For more information, please visit
https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/
int available(void);
Get the number of bytes (characters) available for reading from the serial port. This is data that’s already
arrived and stored in the serial receive buffer.
Serial.read();
Reads incoming serial data.

Any concerns?  support@freenove.com


42 Chapter 3 Bluetooth www.freenove.com █

Chapter 3 Bluetooth
This chapter mainly introduces how to make simple data transmission through Bluetooth of ESP32-S3
WROOM and mobile phones.

Project 3.1 Bluetooth Low Energy Data Passthrough

Component List

ESP32-S3 WROOM x1 USB cable x1

Component knowledge

ESP32-S3's integrated Bluetooth function Bluetooth is a short-distance communication system, which can be
divided into two types, namely Bluetooth Low Energy(BLE) and Classic Bluetooth. There are two modes for
simple data transmission: master mode and slave mode.
Master mode
In this mode, works are done in the master device and it can connect with a slave device. And we can search
and select slave devices nearby to connect with. When a device initiates connection request in master mode,
it requires information of the other Bluetooth devices including their address and pairing passkey. After
finishing pairing, it can connect with them directly.
Slave mode
The Bluetooth module in slave mode can only accept connection request from a host computer, but cannot
initiate a connection request. After connecting with a host device, it can send data to or receive from the host
device.
Bluetooth devices can make data interaction with each other, as one is in master mode and the other in slave
mode. When they are making data interaction, the Bluetooth device in master mode searches and selects
devices nearby to connect to. When establishing connection, they can exchange data. When mobile phones
exchange data with ESP32-S3, they are usually in master mode and ESP32-S3 in slave mode.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 3 Bluetooth 43

Circuit

Connect Freenove ESP32-S3 to the computer using the USB cable.

Any concerns?  support@freenove.com


44 Chapter 3 Bluetooth www.freenove.com █

Sketch

Lightblue
If you can't install Serial Bluetooth on your phone, try LightBlue.If you do not have this software installed on
your phone, you can refer to this link:
https://apps.apple.com/us/app/lightblue/id557428110#?platform=iphone.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 3 Bluetooth 45

Step1. Upload the code of Project 3.1 to ESP32-S3.


Step2. Click on serial monitor.

1 2

Step3. Set baud rate to 115200.

Any concerns?  support@freenove.com


46 Chapter 3 Bluetooth www.freenove.com █

Turn ON Bluetooth on your phone, and open the Lightblue APP.

In the Scan page, swipe down to refresh the name of Bluetooth that the phone searches for. Click
ESP32S3_Bluetooth.

Receive

Click “Receive”. Select the appropriate Data format in the box to the right of Data Format. For example, HEX
for hexadecimal, utf-string for character, Binary for Binary, etc. Then click SUBSCRIBE.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 3 Bluetooth 47

Back to the serial monitor on your computer. You can type anything in the left border of Send, and then click
Send.

And then you can see the mobile Bluetooth has received the message.

Any concerns?  support@freenove.com


48 Chapter 3 Bluetooth www.freenove.com █

Similarly, you can select “Send” on your phone. Set Data format, and then enter anything in the sending box
and click Write to send.

Send

And the computer will receive the message from the mobile Bluetooth.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 3 Bluetooth 49

Any concerns?  support@freenove.com


50 Chapter 3 Bluetooth www.freenove.com █

And now data can be transferred between your mobile phone and computer via ESP32-S3 WROOM.
The following is the program code:
1 #include <BLEDevice.h>
2 #include <BLEServer.h>
3 #include <BLEUtils.h>
4 #include <BLE2902.h>
5 #include <String.h>
6
7 BLECharacteristic *pCharacteristic;
8 bool deviceConnected = false;
9 uint8_t txValue = 0;
10 long lastMsg = 0;
11 String rxload="Test\n";
12
13 #define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
14 #define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
15 #define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
16
17 class MyServerCallbacks: public BLEServerCallbacks {
18 void onConnect(BLEServer* pServer) {
19 deviceConnected = true;
20 };
21 void onDisconnect(BLEServer* pServer) {
22 deviceConnected = false;
23 }
24 };
25
26 class MyCallbacks: public BLECharacteristicCallbacks {
27 void onWrite(BLECharacteristic *pCharacteristic) {
28 std::string rxValue = pCharacteristic->getValue();
29 if (rxValue.length() > 0) {
30 rxload="";
31 for (int i = 0; i < rxValue.length(); i++){
32 rxload +=(char)rxValue[i];
33 }
34 }
35 }
36 };
37
38 void setupBLE(String BLEName){
39 const char *ble_name=BLEName.c_str();
40 BLEDevice::init(ble_name);
41 BLEServer *pServer = BLEDevice::createServer();
42 pServer->setCallbacks(new MyServerCallbacks());

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 3 Bluetooth 51

43 BLEService *pService = pServer->createService(SERVICE_UUID);


44 pCharacteristic=
pService->createCharacteristic(CHARACTERISTIC_UUID_TX,BLECharacteristic::PROPERTY_NOTIFY);
45 pCharacteristic->addDescriptor(new BLE2902());
46 BLECharacteristic *pCharacteristic =
pService->createCharacteristic(CHARACTERISTIC_UUID_RX,BLECharacteristic::PROPERTY_WRITE);
47 pCharacteristic->setCallbacks(new MyCallbacks());
48 pService->start();
49 pServer->getAdvertising()->start();
50 Serial.println("Waiting a client connection to notify...");
51 }
52
53 void setup() {
54 Serial.begin(9600);
55 setupBLE("ESP32S3_Bluetooth");
56 }
57
58 void loop() {
59 long now = millis();
60 if (now - lastMsg > 1000) {
61 if (deviceConnected&&rxload.length()>0) {
62 Serial.println(rxload);
63 rxload="";
64 }
65 if(Serial.available()>0){
66 String str=Serial.readString();
67 const char *newValue=str.c_str();
68 pCharacteristic->setValue(newValue);
69 pCharacteristic->notify();
70 }
71 lastMsg = now;
72 }
73 }
Define the specified UUID number for BLE vendor.
13 #define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
14 #define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
15 #define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"

Any concerns?  support@freenove.com


52 Chapter 3 Bluetooth www.freenove.com █

Write a Callback function for BLE server to manage connection of BLE.


17 class MyServerCallbacks: public BLEServerCallbacks {
18 void onConnect(BLEServer* pServer) {
19 deviceConnected = true;
20 };
21 void onDisconnect(BLEServer* pServer) {
22 deviceConnected = false;
23 }
24 };
Write Callback function with BLE features. When it is called, as the mobile terminal send data to ESP32-S3, it
will store them into reload.
26 class MyCallbacks: public BLECharacteristicCallbacks {
27 void onWrite(BLECharacteristic *pCharacteristic) {
28 std::string rxValue = pCharacteristic->getValue();
29 if (rxValue.length() > 0) {
30 rxload="";
31 for (int i = 0; i < rxValue.length(); i++){
32 rxload +=(char)rxValue[i];
33 }
34 }
35 }
36 };
Initialize the BLE function and name it.
55 setupBLE("ESP32S3_Bluetooth");
When the mobile phone send data to ESP32-S3 via BLE Bluetooth, it will print them out with serial port;
When the serial port of ESP32-S3 receive data, it will send them to mobile via BLE Bluetooth.
59 long now = millis();
60 if (now - lastMsg > 1000) {
61 if (deviceConnected&&rxload.length()>0) {
62 Serial.println(rxload);
63 rxload="";
64 }
65 if(Serial.available()>0){
66 String str=Serial.readString();
67 const char *newValue=str.c_str();
68 pCharacteristic->setValue(newValue);
69 pCharacteristic->notify();
70 }
71 lastMsg = now;
72 }

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 3 Bluetooth 53

The design for creating the BLE server is:


1. Create a BLE Server
2. Create a BLE Service
3. Create a BLE Characteristic on the Service
4. Create a BLE Descriptor on the characteristic
5. Start the service.
6. Start advertising.
38 void setupBLE(String BLEName){
39 const char *ble_name=BLEName.c_str();
40 BLEDevice::init(ble_name);
41 BLEServer *pServer = BLEDevice::createServer();
42 pServer->setCallbacks(new MyServerCallbacks());
43 BLEService *pService = pServer->createService(SERVICE_UUID);
44 pCharacteristic=
pService->createCharacteristic(CHARACTERISTIC_UUID_TX,BLECharacteristic::PROPERTY_NOTIFY);
45 pCharacteristic->addDescriptor(new BLE2902());
46 BLECharacteristic *pCharacteristic =
pService->createCharacteristic(CHARACTERISTIC_UUID_RX,BLECharacteristic::PROPERTY_WRITE);
47 pCharacteristic->setCallbacks(new MyCallbacks());
48 pService->start();
49 pServer->getAdvertising()->start();
50 Serial.println("Waiting a client connection to notify...");
51 }

Any concerns?  support@freenove.com


54 Chapter 4 Read and Write the SDcard www.freenove.com █

Chapter 4 Read and Write the SDcard


An SDcard slot is integrated on the back of the ESP32-S3 WROOM. In this chapter we learn how to use ESP32-
S3 to read and write SDcard.

Project 4.1 SDMMC Test

Component List

ESP32-S3 WROOM x1 USB cable x1 SDcard x1

Component knowledge

SD card read and write method


ESP32-S3 has two ways to use SD card, one is to use the SPI interface to access the SD card, and the other is
to use the SDMMC interface to access the SD card. SPI mode uses 4 IOs to access SD card. The SDMMC has
one-bit bus mode and four-bit bus mode. In one-bit bus mode, SDMMC use 3 IOs to access SD card. In four-
bit bus mode, SDMMC uses 6 IOs to access the SD card.

The above three methods can all be used to access the SD card, the difference is that the access speed is
different.

In the four-bit bus mode of SDMMC, the reading and writing speed of accessing the SD card is the fastest. In
the one-bit bus mode of SDMMC, the access speed is about 80% of the four-bit bus mode. The access speed
of SPI is the slowest, which is about 50% of the four-bit bus mode of SDMMC.

Usually, we recommend using the one-bit bus mode to access the SD card, because in this mode, we only
need to use the least pin IO to access the SD card with good performance and speed.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 4 Read and Write the SDcard 55

Format SD card

Before starting the tutorial, we need to create a drive letter for the blank SD card and format it. This step
requires a card reader and SD card. Please prepare them in advance. Below we will guide you to do it on
different computer systems. You can choose the guide that matches your computer.
Windows
Insert the SD card into the card reader, then insert the card reader into the computer.
In the Windows search box, enter "Disk Management" and select "Create and format hard disk partitions".

Any concerns?  support@freenove.com


56 Chapter 4 Read and Write the SDcard www.freenove.com █

In the new pop-up window, find an unallocated volume close to 1G in size.

Click to select the volume, right-click and select "New Simple Volume".

Click Next.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 4 Read and Write the SDcard 57

You can choose the drive letter on the right, or you can choose the default. By default, just click Next.

File system is FAT(or FAT32). The Allocation unit size is 16K, and the Volume label can be set to any name.
After setting, click Next.

Any concerns?  support@freenove.com


58 Chapter 4 Read and Write the SDcard www.freenove.com █

Click Finish. Wait for the SD card initialization to complete.

At this point, you can see the SD card in This PC.

MAC
Insert the SD card into the card reader, then insert the card reader into the computer. Some computers will
prompt the following information, please click to ignore it.

Find "Disk Utility" in the MAC system and click to open it.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 4 Read and Write the SDcard 59

Select "Generic MassStorageClass Media", note that its size is about 1G. Please do not choose wrong item.
Click "Erase".

Select the configuration as shown in the figure below, and then click "Erase".

Any concerns?  support@freenove.com


60 Chapter 4 Read and Write the SDcard www.freenove.com █

Wait for the formatting to complete. When finished, it will look like the picture below. At this point, you can
see a new disk on the desktop named "SD".

Circuit

Before connecting the USB cable, insert the SD card into the SD card slot on the back of the ESP32-S3.

Connect Freenove ESP32-S3 to the computer using the USB cable.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 4 Read and Write the SDcard 61

Sketch

Sketch_04.1_SDMMC_Test

Compile and upload the code to ESP32-S3-WROOM, open the serial monitor, and press the RST button on
the board.

Any concerns?  support@freenove.com


62 Chapter 4 Read and Write the SDcard www.freenove.com █

You can see the printout as shown below.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 4 Read and Write the SDcard 63

The following is the program code:


1 #include "sd_read_write.h"
2 #include "SD_MMC.h"
3
4 #define SD_MMC_CMD 38 //Please do not modify it.
5 #define SD_MMC_CLK 39 //Please do not modify it.
6 #define SD_MMC_D0 40 //Please do not modify it.
7
8 void setup(){
9 Serial.begin(115200);
10 SD_MMC.setPins(SD_MMC_CLK, SD_MMC_CMD, SD_MMC_D0);
11 if (!SD_MMC.begin("/sdcard", true, true, SDMMC_FREQ_DEFAULT, 5)) {
12 Serial.println("Card Mount Failed");
13 return;
14 }
15 uint8_t cardType = SD_MMC.cardType();
16 if(cardType == CARD_NONE){
17 Serial.println("No SD_MMC card attached");
18 return;
19 }
20 Serial.print("SD_MMC Card Type: ");
21 if(cardType == CARD_MMC){
22 Serial.println("MMC");
23 } else if(cardType == CARD_SD){
24 Serial.println("SDSC");
25 } else if(cardType == CARD_SDHC){
26 Serial.println("SDHC");
27 } else {
28 Serial.println("UNKNOWN");
29 }
30
31 uint64_t cardSize = SD_MMC.cardSize() / (1024 * 1024);
32 Serial.printf("SD_MMC Card Size: %lluMB\n", cardSize);
33
34 listDir(SD_MMC, "/", 0);
35
36 createDir(SD_MMC, "/mydir");
37 listDir(SD_MMC, "/", 0);
38
39 removeDir(SD_MMC, "/mydir");
40 listDir(SD_MMC, "/", 2);
41
42 writeFile(SD_MMC, "/hello.txt", "Hello ");
43 appendFile(SD_MMC, "/hello.txt", "World!\n");

Any concerns?  support@freenove.com


64 Chapter 4 Read and Write the SDcard www.freenove.com █

44 readFile(SD_MMC, "/hello.txt");
45
46 deleteFile(SD_MMC, "/foo.txt");
47 renameFile(SD_MMC, "/hello.txt", "/foo.txt");
48 readFile(SD_MMC, "/foo.txt");
49
50 testFileIO(SD_MMC, "/test.txt");
51
52 Serial.printf("Total space: %lluMB\r\n", SD_MMC.totalBytes() / (1024 * 1024));
53 Serial.printf("Used space: %lluMB\r\n", SD_MMC.usedBytes() / (1024 * 1024));
54 }
55
56 void loop(){
57 delay(10000);
58 }
Add the SD card drive header file.
1 #include "sd_read_write.h"
2 #include "SD_MMC.h"
Defines the drive pins of the SD card. Please do not modify it. Because these pins are fixed.
4 #define SD_MMC_CMD 38 //Please do not modify it.
5 #define SD_MMC_CLK 39 //Please do not modify it.
6 #define SD_MMC_D0 40 //Please do not modify it.
Initialize the serial port function. Sets the drive pin for SDMMC one-bit bus mode.
9 Serial.begin(115200);
10 SD_MMC.setPins(SD_MMC_CLK, SD_MMC_CMD, SD_MMC_D0);
Set the mount point of the SD card, set SDMMC to one-bit bus mode, and set the read and write speed to
20MHz.
11 if (!SD_MMC.begin("/sdcard", true, true, SDMMC_FREQ_DEFAULT, 5)) {
12 Serial.println("Card Mount Failed");
13 return;
14 }
Get the type of SD card and print it out through the serial port.
15 uint8_t cardType = SD_MMC.cardType();
16 if(cardType == CARD_NONE){
17 Serial.println("No SD_MMC card attached");
18 return;
19 }
20 Serial.print("SD_MMC Card Type: ");
21 if(cardType == CARD_MMC){
22 Serial.println("MMC");
23 } else if(cardType == CARD_SD){
24 Serial.println("SDSC");
25 } else if(cardType == CARD_SDHC){
26 Serial.println("SDHC");

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 4 Read and Write the SDcard 65

27 } else {
28 Serial.println("UNKNOWN");
29 }
Call the listDir() function to read the folder and file names in the SD card, and print them out through the
serial port. This function can be found in "sd_read_write.cpp".
34 listDir(SD_MMC, "/", 0);
Call createDir() to create a folder, and call removeDir() to delete a folder.
36 createDir(SD_MMC, "/mydir");
39 removeDir(SD_MMC, "/mydir");
Call writeFile() to write any content to the txt file. If there is no such file, create this file first.
Call appendFile() to append any content to txt.
Call readFile() to read the content in txt and print it via the serial port.
42 writeFile(SD_MMC, "/hello.txt", "Hello ");
43 appendFile(SD_MMC, "/hello.txt", "World!\n");
44 readFile(SD_MMC, "/hello.txt");
Call deleteFile() to delete a specified file.
Call renameFile() to copy a file and rename it.
46 deleteFile(SD_MMC, "/foo.txt");
47 renameFile(SD_MMC, "/hello.txt", "/foo.txt");
Call the testFileIO() function to test the time it takes to read 512 bytes and the time it takes to write 2048*512
bytes of data.
50 testFileIO(SD_MMC, "/test.txt");
Print the total size and used size of the SD card via the serial port.
52 Serial.printf("Total space: %lluMB\r\n", SD_MMC.totalBytes() / (1024 * 1024));
53 Serial.printf("Used space: %lluMB\r\n", SD_MMC.usedBytes() / (1024 * 1024));

Any concerns?  support@freenove.com


66 Chapter 5 WiFi Working Modes www.freenove.com █

Chapter 5 WiFi Working Modes


In this chapter, we'll focus on the WiFi infrastructure for ESP32-S3 WROOM.
ESP32-S3 WROOM has 3 different WiFi operating modes: station mode, AP mode and AP+station mode. All
WiFi programming projects must be configured with WiFi operating mode before using WiFi, otherwise WiFi
cannot be used.

Project 5.1 Station mode

Component List

ESP32-S3 WROOM x1 USB cable x1

Component knowledge

Station mode
When ESP32-S3 selects Station mode, it acts as a WiFi client. It can connect to the router network and
communicate with other devices on the router via WiFi connection. As shown below, the PC is connected to
the router, and if ESP32-S3 wants to communicate with the PC, it needs to be connected to the router.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 5 WiFi Working Modes 67

Circuit

Connect Freenove ESP32-S3 to the computer using the USB cable.

Any concerns?  support@freenove.com


68 Chapter 5 WiFi Working Modes www.freenove.com █

Sketch

Sketch_05.1_Station_mode

Enter the correct Router


name and password.

Because the names and passwords of routers in various places are different, before the Sketch runs, users
need to enter the correct router’s name and password in the box as shown in the illustration above.
After making sure the router name and password are entered correctly, compile and upload codes to ESP32-
S3 WROOM, open serial monitor and set baud rate to 115200. And then it will display as follows:

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 5 WiFi Working Modes 69

When ESP32-S3 WROOM successfully connects to “ssid_Router”, serial monitor will print out the IP address
assigned to ESP32-S3 WROOM by the router.
The following is the program code:
1 #include <WiFi.h>
2
3 const char *ssid_Router = "********"; //Enter the router name
4 const char *password_Router = "********"; //Enter the router password
5
6 void setup(){
7 Serial.begin(115200);
8 delay(2000);
9 Serial.println("Setup start");
10 WiFi.begin(ssid_Router, password_Router);
11 Serial.println(String("Connecting to ")+ssid_Router);
12 while (WiFi.status() != WL_CONNECTED){
13 delay(500);
14 Serial.print(".");
15 }
16 Serial.println("\nConnected, IP address: ");
17 Serial.println(WiFi.localIP());
18 Serial.println("Setup End");
19 }
20
21 void loop() {
22 }
Include the WiFi Library header file of ESP32-S3.
1 #include <WiFi.h>
Enter correct router name and password.
3 const char *ssid_Router = "********"; //Enter the router name
4 const char *password_Router = "********"; //Enter the router password
Set ESP32-S3 in Station mode and connect it to your router.
10 WiFi.begin(ssid_Router, password_Router);
Check whether ESP32-S3 has connected to router successfully every 0.5s.
12 while (WiFi.status() != WL_CONNECTED){
13 delay(500);
14 Serial.print(".");
15 }
Serial monitor prints out the IP address assigned to ESP32-S3 WROOM
17 Serial.println(WiFi.localIP());
Reference
Class Station
Every time when using WiFi, you need to include header file "WiFi.h.".
begin(ssid, password,channel, bssid, connect): ESP32-S3 is used as Station to connect hotspot.
ssid: WiFi hotspot name
Any concerns?  support@freenove.com
70 Chapter 5 WiFi Working Modes www.freenove.com █

password: WiFi hotspot password


channel: WiFi hotspot channel number; communicating through specified channel; optional parameter
bssid: mac address of WiFi hotspot, optional parameter
connect: blloean optional parameter, defaulting to true. If set as false, then ESP32-S3 won't connect WiFi.
config(local_ip, gateway, subnet, dns1, dns2): set static local IP address.
local_ip: station fixed IP address.
subnet:subnet mask
dns1,dns2: optional parameter. define IP address of domain name server
status: obtain the connection status of WiFI
local IP(): obtian IP address in Station mode
disconnect(): disconnect wifi
setAutoConnect(boolen): set automatic connection Every time ESP32-S3 is power on, it will connect WiFi
aitomatically.
setAutoReconnect(boolen): set automatic reconnection Every time ESP32-S3 disconnects WiFi, it will
reconnect to WiFi automatically.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 5 WiFi Working Modes 71

Project 5.2 AP mode

Component List & Circuit

Component List & Circuit are the same as in Project 5.1.

Component knowledge

AP mode
When ESP32-S3 selects AP mode, it creates a hotspot network that is separate from the Internet and waits
for other WiFi devices to connect. As shown in the figure below, ESP32-S3 is used as a hotspot. If a mobile
phone or PC wants to communicate with ESP32-S3, it must be connected to the hotspot of ESP32-S3. Only
after a connection is established with ESP32-S3 can they communicate.

Circuit

Connect Freenove ESP32-S3 to the computer using the USB cable.

Any concerns?  support@freenove.com


72 Chapter 5 WiFi Working Modes www.freenove.com █

Sketch

Set a name and a password


for ESP32S3 AP.

Before the Sketch runs, you can make any changes to the AP name and password for ESP32-S3 in the box as
shown in the illustration above. Of course, you can leave it alone by default.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 5 WiFi Working Modes 73

Compile and upload codes to ESP32-S3 WROOM, open the serial monitor and set the baud rate to 115200.
And then it will display as follows.

When observing the print information of the serial monitor, turn on the WiFi scanning function of your phone,
and you can see the ssid_AP on ESP32-S3, which is called "WiFi_Name" in this Sketch. You can enter the
password "12345678" to connect it or change its AP name and password by modifying Sketch.

Any concerns?  support@freenove.com


74 Chapter 5 WiFi Working Modes www.freenove.com █

Sketch_05.2_AP_mode
The following is the program code:
1 #include <WiFi.h>
2
3 const char *ssid_AP = "WiFi_Name"; //Enter the router name
4 const char *password_AP = "12345678"; //Enter the router password
5
6 IPAddress local_IP(192,168,1,100);//Set the IP address of ESP32-S3 itself
7 IPAddress gateway(192,168,1,10); //Set the gateway of ESP32-S3 itself
8 IPAddress subnet(255,255,255,0); //Set the subnet mask for ESP32-S3 itself
9
10 void setup(){
11 Serial.begin(115200);
12 delay(2000);
13 Serial.println("Setting soft-AP configuration ... ");
14 WiFi.disconnect();
15 WiFi.mode(WIFI_AP);
16 Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");
17 Serial.println("Setting soft-AP ... ");
18 boolean result = WiFi.softAP(ssid_AP, password_AP);
19 if(result){
20 Serial.println("Ready");
21 Serial.println(String("Soft-AP IP address = ") + WiFi.softAPIP().toString());
22 Serial.println(String("MAC address = ") + WiFi.softAPmacAddress().c_str());
23 }else{
24 Serial.println("Failed!");
25 }
26 Serial.println("Setup End");
27 }
28
29 void loop() {
30 }
Include WiFi Library header file of ESP32-S3.
1 #include <WiFi.h>
Enter correct AP name and password.
3 const char *ssid_AP = "WiFi_Name"; //Enter the router name
4 const char *password_AP = "12345678"; //Enter the router password
Set ESP32-S3 in AP mode.
15 WiFi.mode(WIFI_AP);
Configure IP address, gateway and subnet mask for ESP32-S3.
16 WiFi.softAPConfig(local_IP, gateway, subnet)
Turn on an AP in ESP32-S3, whose name is set by ssid_AP and password is set by password_AP.
18 WiFi.softAP(ssid_AP, password_AP);

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 5 WiFi Working Modes 75

Check whether the AP is turned on successfully. If yes, print out IP and MAC address of AP established by
ESP32-S3. If no, print out the failure prompt.
19 if(result){
20 Serial.println("Ready");
21 Serial.println(String("Soft-AP IP address = ") + WiFi.softAPIP().toString());
22 Serial.println(String("MAC address = ") + WiFi.softAPmacAddress().c_str());
23 }else{
24 Serial.println("Failed!");
25 }
26 Serial.println("Setup End");
Reference
Class AP
Every time when using WiFi, you need to include header file "WiFi.h.".
softAP(ssid, password, channel, ssid_hidden, max_connection):
ssid: WiFi hotspot name
password: WiFi hotspot password
channel: Number of WiFi connection channels, range 1-13. The default is 1.
ssid_hidden: Whether to hide WiFi name from scanning by other devices. The default is not hide.
max_connection: Maximum number of WiFi connected devices. The range is 1-4. The default is 4.
softAPConfig(local_ip, gateway, subnet): set static local IP address.
local_ip: station fixed IP address.
Gateway: gateway IP address
subnet:subnet mask
softAP(): obtian IP address in AP mode
softAPdisconnect (): disconnect AP mode.

Any concerns?  support@freenove.com


76 Chapter 5 WiFi Working Modes www.freenove.com █

Project 5.3 AP+Station mode

Component List

ESP32-S3 WROOM x1 USB cable x1

Component knowledge

AP+Station mode
In addition to AP mode and station mode, ESP32-S3 can also use AP mode and station mode at the same
time. This mode contains the functions of the previous two modes. Turn on ESP32-S3's station mode, connect
it to the router network, and it can communicate with the Internet via the router. At the same time, turn on
its AP mode to create a hotspot network. Other WiFi devices can choose to connect to the router network or
the hotspot network to communicate with ESP32-S3.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 5 WiFi Working Modes 77

Circuit

Connect Freenove ESP32-S3 to the computer using the USB cable.

Sketch

Sketch_05.3_AP_Station_mode

Please enter the correct


names and passwords of
Router and AP.

It is analogous to Project 5.1 and Project 5.2. Before running the Sketch, you need to modify ssid_Router,
password_Router, ssid_AP and password_AP shown in the box of the illustration above.

Any concerns?  support@freenove.com


78 Chapter 5 WiFi Working Modes www.freenove.com █

After making sure that Sketch is modified correctly, compile and upload codes to ESP32-S3 WROOM, open
serial monitor and set baud rate to 115200. And then it will display as follows:

When observing the print information of the serial monitor, turn on the WiFi scanning function of your phone,
and you can see the ssid_AP on ESP32-S3.

The following is the program code:


1 #include <WiFi.h>
2
3 const char *ssid_Router = "********"; //Enter the router name
4 const char *password_Router = "********"; //Enter the router password
5 const char *ssid_AP = "WiFi_Name"; //Enter the AP name
6 const char *password_AP = "12345678"; //Enter the AP password
7
8 void setup(){
9 Serial.begin(115200);
10 Serial.println("Setting soft-AP configuration ... ");

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 5 WiFi Working Modes 79

11 WiFi.disconnect();
12 WiFi.mode(WIFI_AP);
13 Serial.println("Setting soft-AP ... ");
14 boolean result = WiFi.softAP(ssid_AP, password_AP);
15 if(result){
16 Serial.println("Ready");
17 Serial.println(String("Soft-AP IP address = ") + WiFi.softAPIP().toString());
18 Serial.println(String("MAC address = ") + WiFi.softAPmacAddress().c_str());
19 }else{
20 Serial.println("Failed!");
21 }
22
23 Serial.println("\nSetting Station configuration ... ");
24 WiFi.begin(ssid_Router, password_Router);
25 Serial.println(String("Connecting to ")+ ssid_Router);
26 while (WiFi.status() != WL_CONNECTED){
27 delay(500);
28 Serial.print(".");
29 }
30 Serial.println("\nConnected, IP address: ");
31 Serial.println(WiFi.localIP());
32 Serial.println("Setup End");
33 }
34
35 void loop() {
36 }

Any concerns?  support@freenove.com


80 Chapter 6 TCP/IP www.freenove.com █

Chapter 6 TCP/IP
In this chapter, we will introduce how ESP32-S3 implements network communications based on TCP/IP
protocol. There are two roles in TCP/IP communication, namely Server and Client, which will be implemented
respectively with two projects in this chapter.

Project 6.1 As Client

In this section, ESP32-S3 is used as Client to connect Server on the same LAN and communicate with it.

Component List

ESP32-S3 WROOM x1 USB cable x1

Component knowledge

TCP connection
Before transmitting data, TCP needs to establish a logical connection between the sending end and the
receiving end. It provides reliable and error-free data transmission between the two computers. In the TCP
connection, the client and the server must be clarified. The client sends a connection request to the server,
and each time such a request is proposed, a "three-times handshake" is required.

Three-times handshake: In the TCP protocol, during the preparation phase of sending data, the client and the
server interact three times to ensure the reliability of the connection, which is called "three-times handshake".
The first handshake, the client sends a connection request to the server and waits for the server to confirm.
The second handshake, the server sends a response back to the client informing that it has received the
connection request.
The third handshake, the client sends a confirmation message to the server again to confirm the connection.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 6 TCP/IP 81

the first handshake

the second handshake

the third handshake

TCP is a connection-oriented, low-level transmission control protocol. After TCP establishes a connection, the
client and server can send and receive messages to each other, and the connection will always exist as long
as the client or server does not initiate disconnection. Each time one party sends a message, the other party
will reply with an ack signal.

The client sends a data


message, and the server
replies with a
confirmation signal.

The server sends a data


message, and the client
replies with a
confirmation signal.

Any concerns?  support@freenove.com


82 Chapter 6 TCP/IP www.freenove.com █

Install Processing
In this tutorial, we use Processing to build a simple TCP/IP communication platform.
If you've not installed Processing, you can download it by clicking https://processing.org/download/. You can
choose an appropriate version to download according to your PC system.

Unzip the downloaded file to your computer. Click "processing.exe" as the figure below to run this software.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 6 TCP/IP 83

Use Server mode for communication


Install ControlP5.

Any concerns?  support@freenove.com


84 Chapter 6 TCP/IP www.freenove.com █

Open the “Freenove_ESP32_S3_WROVER_Board\Sketches\Sketches\Sketch_06.1_WiFiClient\


sketchWiFi\sketchWiFi.pde”, and click "Run".

Stop

Run

The new pop-up interface is as follows. If ESP32-S3 is used as client, select TCP SERVER mode for sketchWiFi.

Server mode

Receiving
Local IP address
box

Local port
number
Clear receive

Send box
Listening
Clear send

Send button

When sketchWiFi selects TCP SERVER mode, ESP32-S3 Sketch needs to be changed according to
sketchWiFi's displaying of LOCAL IP or LOCAL PORT.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 6 TCP/IP 85

If ESP32-S3 serves as server, select TCP CLIENT mode for sketchWiFi.

Client mode

Remote IP
address

Remote port
number

When sketchWiFi selects TCP CLIENT mode, the LOCAL IP and LOCAL PORT of sketchWiFi need to be
changed according to the IP address and port number printed by the serial monitor.

Mode selection: select Server mode/Client mode.


IP address: In server mode, this option does not need to be filled in, and the computer will automatically
obtain the IP address.
In client mode, fill in the remote IP address to be connected.
Port number: In server mode, fill in a port number for client devices to make an access connection.
In client mode, fill in port number given by the Server devices to make an access connection.
Start button: In server mode, push the button, then the computer will serve as server and open a port number
for client to make access connection. During this period, the computer will keep monitoring.
In client mode, before pushing the button, please make sure the server is on, remote IP address
and remote port number is correct; push the button, and the computer will make access
connection to the remote port number of the remote IP as a client.
clear receive: clear out the content in the receiving text box
clear send: clear out the content in the sending text box
Sending button: push the sending button, the computer will send the content in the text box to others.

Any concerns?  support@freenove.com


86 Chapter 6 TCP/IP www.freenove.com █

Circuit

Connect Freenove ESP32-S3 to the computer using the USB cable.

Sketch

Before running the Sketch, please open “sketchWiFi.pde.” first, and click “Run”.

The newly pop up window will use the computer’s IP address by default and open a data monitor port.

Next, open Sketch_06.1_WiFiClient.ino. Before running it, please change the following information based on
"LOCAL IP" and "LOCAL PORT" in the figure above.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 6 TCP/IP 87

REMOTE_IP needs to be filled in according to the interface of sketchWiFi.pde. Taking this tutorial as an
example, its REMOTE_IP is “192.168.1.133”. Generally, by default, the ports do not need to change its value.

Click LISTENING, turn on TCP SERVER's data listening function and wait for ESP32-S3 to connect.

Click it

Compile and upload code to ESP32-S3 WROOM, open the serial monitor and set the baud rate to 115200.
ESP32-S3 connects router, obtains IP address and sends access request to server IP address on the same LAN
till the connection is successful. When connect successfully, ESP32-S3 can send messages to server.

Any concerns?  support@freenove.com


88 Chapter 6 TCP/IP www.freenove.com █

ESP32-S3 connects with TCP SERVER, and TCP SERVER receives messages from ESP32-S3, as shown in the
figure below.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 6 TCP/IP 89

Sketch_06.1_As_Client
The following is the program code:
1 #include <WiFi.h>
2
3 const char *ssid_Router = "********"; //Enter the router name
4 const char *password_Router = "********"; //Enter the router password
5 #define REMOTE_IP "********" //input the remote server which is you want to connect
#define REMOTE_PORT 8888 //input the remote port which is the remote provide
6 WiFiClient client;
7
8 void setup() {
9 Serial.begin(115200);
10 delay(10);
11
12 WiFi.begin(ssid_Router, password_Router);
13 Serial.print("\nWaiting for WiFi... ");
14 while (WiFi.status() != WL_CONNECTED) {
15 Serial.print(".");
16 delay(500);
17 }
18 Serial.println("");
19 Serial.println("WiFi connected");
20 Serial.println("IP address: ");
21 Serial.println(WiFi.localIP());
22 delay(500);
23
24 Serial.print("Connecting to ");
25 Serial.println(REMOTE_IP);
26
27 while (!client.connect(REMOTE_IP, REMOTE_PORT)) {
28 Serial.println("Connection failed.");
29 Serial.println("Waiting a moment before retrying...");
30 }
31 Serial.println("Connected");
32 client.print("Hello\n");
33 client.print("This is my IP.\n");
34 }
35
36 void loop() {
37 if (client.available() > 0) {
38 delay(20);
39 //read back one line from the server
40 String line = client.readString();
41 Serial.println(REMOTE_IP + String(":") + line);

Any concerns?  support@freenove.com


90 Chapter 6 TCP/IP www.freenove.com █

42 }
43 if (Serial.available() > 0) {
44 delay(20);
45 String line = Serial.readString();
46 client.print(line);
47 }
48 if (client.connected () == 0) {
49 client.stop();
50 WiFi.disconnect();
51 }
52 }
Add WiFi function header file.
1 #include <WiFi.h>
Enter the actual router name, password, remote server IP address, and port number.
3 const char *ssid_Router = "********"; //Enter the router name
4 const char *password_Router = "********"; //Enter the router password
5 #define REMOTE_IP "********" //input the remote server which is you want to connect
6 #define REMOTE_PORT 8888 //input the remote port which is the remote provide
Apply for the method class of WiFiClient.
7 WiFiClient client;
Connect specified WiFi until it is successful. If the name and password of WiFi are correct but it still fails to
connect, please push the reset key.
13 WiFi.begin(ssid_Router, password_Router);
14 Serial.print("\nWaiting for WiFi... ");
15 while (WiFi.status() ! = WL_CONNECTED) {
16 Serial.print(".");
17 delay(500);
18 }
Send connection request to remote server until connect successfully. When connect successfully, print out the
connecting prompt on the serial monitor and send messages to remote server.
28 while (!client.connect(REMOTE_IP, REMOTE_PORT)) {//Connect to Server
29 Serial.println("Connection failed.");
30 Serial.println("Waiting a moment before retrying...");
31 }
32 Serial.println("Connected");
33 client.print("Hello\n");
When ESP32-S3 receive messages from servers, it will print them out via serial port; Users can also send
messages to servers from serial port.
37 if (client.available() > 0) {
38 delay(20);
39 //read back one line from the server
40 String line = client.readString();
41 Serial.println(REMOTE_IP + String(":") + line);
42 }

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 6 TCP/IP 91

43 if (Serial.available() > 0) {
44 delay(20);
45 String line = Serial.readString();
46 client.print(line);
47 }
If the server is disconnected, turn off WiFi of ESP32-S3.
48 if (client.connected () == false) {
49 client.stop();
50 WiFi.disconnect();
51 }
Reference
Class Client
Every time when using Client, you need to include header file "WiFi.h."
connect(ip, port, timeout)/connect(*host, port, timeout): establish a TCP connection.
ip, *host:ip address of target server
port: port number of target server
timeout: connection timeout
connected(): judge whether client is connecting. If return value is 1, then connect successfully; If return
value is 0, then fail to connect.
stop(): stop tcp connection
print(): send data to server connecting to client
available(): return to the number of bytes readable in receive buffer, if no, return to 0 or -1.
read(): read one byte of data in receive buffer
readString(): read string in receive buffer

Any concerns?  support@freenove.com


92 Chapter 6 TCP/IP www.freenove.com █

Project 6.2 As Server

In this section, ESP32-S3 is used as a server to wait for the connection and communication of client on the
same LAN.

Component List

ESP32-S3 WROOM x1 USB cable x1

Circuit

Connect Freenove ESP32-S3 to the computer using a USB cable.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 6 TCP/IP 93

Sketch

Before running Sketch, please modify the contents of the box below first.
Sketch_06.2_As_Server

Compile and upload code to ESP32-S3 WROOM board, open the serial monitor and set the baud rate to
115200. Turn on server mode for ESP32-S3, waiting for the connection of other devices on the same LAN.
Once a device connects to server successfully, they can send messages to each other.
If the ESP32-S3 fails to connect to router, press the reset button as shown below and wait for ESP32-S3 to
run again.

Any concerns?  support@freenove.com


94 Chapter 6 TCP/IP www.freenove.com █

Serial Monitor

IP address and
serial port

Processing:
Open the “Freenove_ESP32_S3_WROVER_Board\Sketches\Sketches\Sketch_06.2_WiFiServer\
sketchWiFi\sketchWiFi.pde”.
Based on the messages printed by the serial monitor, enter correct IP address and serial port in Processing to
establish connection and make communication.

Enter IP address and


serial port of the serial
monitor.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 6 TCP/IP 95

The following is the program code:


1 #include <WiFi.h>
2
3 #define port 80
4 const char *ssid_Router = "********"; //input your wifi name
5 const char *password_Router = "********"; //input your wifi passwords
6 WiFiServer server(port);
7
8 void setup()
9 {
10 Serial.begin(115200);
11 Serial.printf("\nConnecting to ");
12 Serial.println(ssid_Router);
13 WiFi.disconnect();
14 WiFi.begin(ssid_Router, password_Router);
15 delay(1000);
16 while (WiFi.status() != WL_CONNECTED) {
17 delay(500);
18 Serial.print(".");
19 }
20 Serial.println("");
21 Serial.println("WiFi connected.");
22 Serial.print("IP address: ");
23 Serial.println(WiFi.localIP());
24 Serial.printf("IP port: %d\n",port);
25 server.begin(port);
26 WiFi.setAutoConnect(true);
27 WiFi.setAutoReconnect(true);
28 }
29
30 void loop(){
31 WiFiClient client = server.available(); // listen for incoming clients
32 if (client) { // if you get a client
33 Serial.println("Client connected.");
34 while (client.connected()) { // loop while the client's connected
35 if (client.available()) { // if there's bytes to read from the
client
36 Serial.println(client.readStringUntil('\n')); // print it out the serial monitor
37 while(client.read()>0); // clear the wifi receive area cache
38 }
39 if(Serial.available()){ // if there's bytes to read from the
serial monitor
40 client.print(Serial.readStringUntil('\n')); // print it out the client.
41 while(Serial.read()>0); // clear the wifi receive area cache

Any concerns?  support@freenove.com


96 Chapter 6 TCP/IP www.freenove.com █

42 }
43 }
44 client.stop(); // stop the client connecting.
45 Serial.println("Client Disconnected.");
46 }
47 }
Apply for method class of WiFiServer.
6 WiFiServer server(port); //Apply for a Server object whose port number is 80
Connect specified WiFi until it is successful. If the name and password of WiFi are correct but it still fails to
connect, please push the reset key.
13 WiFi.disconnect();
14 WiFi.begin(ssid_Router, password_Router);
15 delay(1000);
16 while (WiFi.status() != WL_CONNECTED) {
17 delay(500);
18 Serial.print(".");
19 }
20 Serial.println("");
21 Serial.println("WiFi connected.");
Print out the IP address and port number of ESP32-S3.
22 Serial.print("IP address: ");
23 Serial.println(WiFi.localIP()); //print out IP address of ESP32-S3
24 Serial.printf("IP port: %d\n",port); //Print out ESP32-S3's port number
Turn on server mode of ESP32-S3, start automatic connection and turn on automatic reconnection.
25 server.begin(); //Turn ON ESP32-S3 as Server mode
26 WiFi.setAutoConnect(true);
27 WiFi.setAutoReconnect(true);
When ESP32-S3 receive messages from servers, it will print them out via serial port; Users can also send
messages to servers from serial port.
35 if (client.available()) { // if there's bytes to read from the
client
36 Serial.println(client.readStringUntil('\n')); // print it out the serial monitor
37 while(client.read()>0); // clear the wifi receive area cache
38 }
39 if(Serial.available()){ // if there's bytes to read from the
serial monitor
40 client.print(Serial.readStringUntil('\n')); // print it out the client.
41 while(Serial.read()>0); // clear the wifi receive area cache
42 }

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 6 TCP/IP 97

Reference
Class Server
Every time use Server functionality, we need to include header file"WiFi.h".
WiFiServer(uint16_t port=80, uint8_t max_clients=4): create a TCP Server.
port: ports of Server; range from 0 to 65535 with the default number as 80.
max_clients: maximum number of clients with default number as 4.
begin(port): start the TCP Server.
port: ports of Server; range from 0 to 65535 with the default number as 0.
setNoDelay(bool nodelay): whether to turn off the delay sending functionality.
nodelay: true stands for forbidden Nagle algorithm.
close(): close tcp connection.
stop(): stop tcp connection.

Any concerns?  support@freenove.com


98 Chapter 7 Camera Web Server www.freenove.com █

Chapter 7 Camera Web Server


In this section, we'll use ESP32-S3's video function as an example to study.

Project 7.1 Camera Web Server

Connect ESP32-S3 using USB and check its IP address through serial monitor. Use web page to access IP
address to obtain video and image data.

Component List

ESP32-S3 WROOM x1 USB cable x1

Circuit

Connect Freenove ESP32-S3 to the computer using the USB cable.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 7 Camera Web Server 99

Sketch

Sketch_07.1_As_CameraWebServer

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 Sketch can compile and work successfully.

Compile and upload codes to ESP32-S3, open the serial monitor and set the baud rate to 115200, and the
serial monitor will print out a network link address.

If your ESP32-S3 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 ESP32-S3 WROOM to wait for a successful connection prompt.

Any concerns?  support@freenove.com


100 Chapter 7 Camera Web Server www.freenove.com █

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 ESP32-
S3's IP.

enter IP address

select pixel of the picture

adjust camera parameters

set camera left and


right, up and down

crop the picture turn on video


transmission

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 7 Camera Web Server 101

Click on Start Stream. The effect is shown in the image below.

Note: If sketch compilation fails due to ESP32-S3 support package, follow the steps of the image to
open the CameraWebServer. This sketch is the same as described in the tutorial above.

Any concerns?  support@freenove.com


102 Chapter 7 Camera Web Server www.freenove.com █

The following is the main program code. You need include other code files in the same folder when write
your own code.
1 #include "esp_camera.h"
2 #include <WiFi.h>
3
4 // ===================
5 // Select camera model
6 // ===================
7 //#define CAMERA_MODEL_WROVER_KIT // Has PSRAM
8 //#define CAMERA_MODEL_ESP_EYE // Has PSRAM
9 #define CAMERA_MODEL_ESP32S3_EYE // Has PSRAM
10 //#define CAMERA_MODEL_M5STACK_PSRAM // Has PSRAM
11 //#define CAMERA_MODEL_M5STACK_V2_PSRAM // M5Camera version B Has PSRAM
12 //#define CAMERA_MODEL_M5STACK_WIDE // Has PSRAM
13 //#define CAMERA_MODEL_M5STACK_ESP32CAM // No PSRAM
14 //#define CAMERA_MODEL_M5STACK_UNITCAM // No PSRAM
15 //#define CAMERA_MODEL_AI_THINKER // Has PSRAM
16 //#define CAMERA_MODEL_TTGO_T_JOURNAL // No PSRAM
17 // ** Espressif Internal Boards **
18 //#define CAMERA_MODEL_ESP32_CAM_BOARD
19 //#define CAMERA_MODEL_ESP32S2_CAM_BOARD
20 //#define CAMERA_MODEL_ESP32S3_CAM_LCD
21
22 #include "camera_pins.h"
23
24 // ===========================
25 // Enter your WiFi credentials
26 // ===========================
27 const char* ssid = "********";
28 const char* password = "********";
29
30 void startCameraServer();
31
32 void setup() {
33 Serial.begin(115200);
34 Serial.setDebugOutput(true);
35 Serial.println();
36
37 camera_config_t config;
38 config.ledc_channel = LEDC_CHANNEL_0;
39 config.ledc_timer = LEDC_TIMER_0;
40 config.pin_d0 = Y2_GPIO_NUM;
41 config.pin_d1 = Y3_GPIO_NUM;
42 config.pin_d2 = Y4_GPIO_NUM;

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 7 Camera Web Server 103

43 config.pin_d3 = Y5_GPIO_NUM;
44 config.pin_d4 = Y6_GPIO_NUM;
45 config.pin_d5 = Y7_GPIO_NUM;
46 config.pin_d6 = Y8_GPIO_NUM;
47 config.pin_d7 = Y9_GPIO_NUM;
48 config.pin_xclk = XCLK_GPIO_NUM;
49 config.pin_pclk = PCLK_GPIO_NUM;
50 config.pin_vsync = VSYNC_GPIO_NUM;
51 config.pin_href = HREF_GPIO_NUM;
52 config.pin_sscb_sda = SIOD_GPIO_NUM;
53 config.pin_sscb_scl = SIOC_GPIO_NUM;
54 config.pin_pwdn = PWDN_GPIO_NUM;
55 config.pin_reset = RESET_GPIO_NUM;
56 config.xclk_freq_hz = 20000000;
57 config.frame_size = FRAMESIZE_UXGA;
58 config.pixel_format = PIXFORMAT_JPEG; // for streaming
59 config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
60 config.fb_location = CAMERA_FB_IN_PSRAM;
61 config.jpeg_quality = 12;
62 config.fb_count = 1;
63
64 // if PSRAM IC present, init with UXGA resolution and higher JPEG quality
65 // for larger pre-allocated frame buffer.
66 if(psramFound()){
67 config.jpeg_quality = 10;
68 config.fb_count = 2;
69 config.grab_mode = CAMERA_GRAB_LATEST;
70 } else {
71 // Limit the frame size when PSRAM is not available
72 config.frame_size = FRAMESIZE_SVGA;
73 config.fb_location = CAMERA_FB_IN_DRAM;
74 }
75
76 // camera init
77 esp_err_t err = esp_camera_init(&config);
78 if (err != ESP_OK) {
79 Serial.printf("Camera init failed with error 0x%x", err);
80 return;
81 }
82
83 sensor_t * s = esp_camera_sensor_get();
84 // initial sensors are flipped vertically and colors are a bit saturated
85 s->set_vflip(s, 1); // flip it back
86 s->set_brightness(s, 1); // up the brightness just a bit

Any concerns?  support@freenove.com


104 Chapter 7 Camera Web Server www.freenove.com █

87 s->set_saturation(s, -1); // lower the saturation


88
89 WiFi.begin(ssid, password);
90 WiFi.setSleep(false);
91
92 while (WiFi.status() != WL_CONNECTED) {
93 delay(500);
94 Serial.print(".");
95 }
96 Serial.println("");
97 Serial.println("WiFi connected");
98
99 startCameraServer();
100
101 Serial.print("Camera Ready! Use 'http://");
102 Serial.print(WiFi.localIP());
103 Serial.println("' to connect");
104 }
105
106 void loop() {
107 // Do nothing. Everything is done in another task by the web server
108 delay(10000);
109 }

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 7 Camera Web Server 105

Add procedure files and API interface files related to ESP32-S3 camera.
1 #include "esp_camera.h"
2 #include <WiFi.h>

9 #define CAMERA_MODEL_ESP32S3_EYE // Has PSRAM

11 #include "camera_pins.h"
Enter the name and password of the router
13 const char *ssid = "********"; //input your wifi name
14 const char *password = "********"; //input your wifi passwords
Initialize serial port, set baud rate to 115200; open the debug and output function of the serial.
21 Serial.begin(115200);
22 Serial.setDebugOutput(true);
23 Serial.println();
Configure parameters including interface pins of the camera. Note: It is generally not recommended to change
them.
37 camera_config_t config;
38 config.ledc_channel = LEDC_CHANNEL_0;
39 config.ledc_timer = LEDC_TIMER_0;
40 config.pin_d0 = Y2_GPIO_NUM;
41 config.pin_d1 = Y3_GPIO_NUM;
42 config.pin_d2 = Y4_GPIO_NUM;
43 config.pin_d3 = Y5_GPIO_NUM;
44 config.pin_d4 = Y6_GPIO_NUM;
45 config.pin_d5 = Y7_GPIO_NUM;
46 config.pin_d6 = Y8_GPIO_NUM;
47 config.pin_d7 = Y9_GPIO_NUM;
48 config.pin_xclk = XCLK_GPIO_NUM;
49 config.pin_pclk = PCLK_GPIO_NUM;
50 config.pin_vsync = VSYNC_GPIO_NUM;
51 config.pin_href = HREF_GPIO_NUM;
52 config.pin_sscb_sda = SIOD_GPIO_NUM;
53 config.pin_sscb_scl = SIOC_GPIO_NUM;
54 config.pin_pwdn = PWDN_GPIO_NUM;
55 config.pin_reset = RESET_GPIO_NUM;
56 config.xclk_freq_hz = 20000000;
57 config.frame_size = FRAMESIZE_UXGA;
58 config.pixel_format = PIXFORMAT_JPEG; // for streaming
59 config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
60 config.fb_location = CAMERA_FB_IN_PSRAM;
61 config.jpeg_quality = 12;
62 config.fb_count = 1;

Any concerns?  support@freenove.com


106 Chapter 7 Camera Web Server www.freenove.com █

ESP32-S3 connects to the router and prints a successful connection prompt. If it has not been successfully
connected, press the reset key on the ESP32-S3 WROOM.
89 WiFi.begin(ssid, password);
90 WiFi.setSleep(false);
91
92 while (WiFi.status() != WL_CONNECTED) {
93 delay(500);
94 Serial.print(".");
95 }
96 Serial.println("");
97 Serial.println("WiFi connected");
Open the video streams server function of the camera and print its IP address via serial port.
99 startCameraServer();
100
101 Serial.print("Camera Ready! Use 'http://");
102 Serial.print(WiFi.localIP());
103 Serial.println("' to connect");
Configure the display image information of the camera.
The set_vflip() function sets whether the image is flipped 180°, with 0 for no flip and 1 for flip 180°.
The set_brightness() function sets the brightness of the image, with values ranging from -2 to 2.
The set_saturation() function sets the color saturation of the image, with values ranging from -2 to 2.
36 sensor_t * s = esp_camera_sensor_get();
37 s->set_vflip(s, 1); //flip it back
38 s->set_brightness(s, 1); //up the blightness just a bit
39 s->set_saturation(s, -1); //lower the saturation
Modify the resolution and sharpness of the images captured by the camera. The sharpness ranges from 10 to
63, and the smaller the number, the sharper the picture. The larger the number, the blurrier the picture. Please
refer to the table below.
config.frame_size = FRAMESIZE_VGA;
config.jpeg_quality = 10;
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

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 7 Camera Web Server 107

Project 7.2 Video Web Server

Connect to ESP32-S3 using USB and view its IP address through a serial monitor. Access IP addresses through
web pages to obtain real-time video data.

Component List

ESP32-S3 WROOM x1 USB cable x1 SDcard x1

Circuit

Connect Freenove ESP32-S3 to the computer using the USB cable.

Any concerns?  support@freenove.com


108 Chapter 7 Camera Web Server www.freenove.com █

Sketch

Sketch_07.2_As_VideoWebServer

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 Sketch can compile and work successfully.

Compile and upload codes to ESP32-S3, open the serial monitor and set the baud rate to 115200, and the
serial monitor will print out a network link address.

If your ESP32-S3 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 ESP32-S3 WROOM to wait for a successful connection prompt.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 7 Camera Web Server 109

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 ESP32-
S3's IP.

The effect is shown in the image below.

Enter IP address.

Save it to SDcard.

The following is the main program code. You need include other code files in the same folder when write
your own code.
1 #include "esp_camera.h"
2 #include <WiFi.h>
3
4 // Select camera model
5 #define CAMERA_MODEL_ESP32S3_EYE // Has PSRAM
6 #include "camera_pins.h"
7

Any concerns?  support@freenove.com


110 Chapter 7 Camera Web Server www.freenove.com █

8 const char* ssid = "********"; //input your wifi name


9 const char* password = "********"; //input your wifi passwords
10 void startCameraServer();
11
12 void setup() {
13 Serial.begin(115200);
14 Serial.setDebugOutput(true);
15 Serial.println();
16
17 camera_config_t config;
18 config.ledc_channel = LEDC_CHANNEL_0;
19 config.ledc_timer = LEDC_TIMER_0;
20 config.pin_d0 = Y2_GPIO_NUM;
21 config.pin_d1 = Y3_GPIO_NUM;
22 config.pin_d2 = Y4_GPIO_NUM;
23 config.pin_d3 = Y5_GPIO_NUM;
24 config.pin_d4 = Y6_GPIO_NUM;
25 config.pin_d5 = Y7_GPIO_NUM;
26 config.pin_d6 = Y8_GPIO_NUM;
27 config.pin_d7 = Y9_GPIO_NUM;
28 config.pin_xclk = XCLK_GPIO_NUM;
29 config.pin_pclk = PCLK_GPIO_NUM;
30 config.pin_vsync = VSYNC_GPIO_NUM;
31 config.pin_href = HREF_GPIO_NUM;
32 config.pin_sscb_sda = SIOD_GPIO_NUM;
33 config.pin_sscb_scl = SIOC_GPIO_NUM;
34 config.pin_pwdn = PWDN_GPIO_NUM;
35 config.pin_reset = RESET_GPIO_NUM;
36 config.xclk_freq_hz = 20000000;
37 config.frame_size = FRAMESIZE_UXGA;
38 config.pixel_format = PIXFORMAT_JPEG; // for streaming
39 config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
40 config.fb_location = CAMERA_FB_IN_PSRAM;
41 config.jpeg_quality = 12;
42 config.fb_count = 1;
43
44 // if PSRAM IC present, init with UXGA resolution and higher JPEG quality
45 // for larger pre-allocated frame buffer.
46 if(psramFound()){
47 config.jpeg_quality = 10;
48 config.fb_count = 2;
49 config.grab_mode = CAMERA_GRAB_LATEST;
50 } else {
51 // Limit the frame size when PSRAM is not available

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 7 Camera Web Server 111

52 config.frame_size = FRAMESIZE_SVGA;
53 config.fb_location = CAMERA_FB_IN_DRAM;
54 }
55
56 // camera init
57 esp_err_t err = esp_camera_init(&config);
58 if (err != ESP_OK) {
59 Serial.printf("Camera init failed with error 0x%x", err);
60 return;
61 }
62
63 sensor_t * s = esp_camera_sensor_get();
64 // initial sensors are flipped vertically and colors are a bit saturated
65 s->set_vflip(s, 1); // flip it back
66 s->set_brightness(s, 1); // up the brightness just a bit
67 s->set_saturation(s, 0); // lower the saturation
68
69 WiFi.begin(ssid, password);
70
71 while (WiFi.status() != WL_CONNECTED) {
72 delay(500);
73 Serial.print(".");
74 }
75 Serial.println("");
76 Serial.println("WiFi connected");
77
78 startCameraServer();
79
80 Serial.print("Camera Ready! Use 'http://");
81 Serial.print(WiFi.localIP());
82 Serial.println("' to connect");
83 }
84
85 void loop() {
86 // put your main code here, to run repeatedly:
87 delay(10000);
88 }

Configure parameters including interface pins of the camera. Note: It is generally not recommended to change
them.
17 camera_config_t config;
18 config.ledc_channel = LEDC_CHANNEL_0;
19 config.ledc_timer = LEDC_TIMER_0;
20 config.pin_d0 = Y2_GPIO_NUM;

Any concerns?  support@freenove.com


112 Chapter 7 Camera Web Server www.freenove.com █

21 config.pin_d1 = Y3_GPIO_NUM;
22 config.pin_d2 = Y4_GPIO_NUM;
23 config.pin_d3 = Y5_GPIO_NUM;
24 config.pin_d4 = Y6_GPIO_NUM;
25 config.pin_d5 = Y7_GPIO_NUM;
26 config.pin_d6 = Y8_GPIO_NUM;
27 config.pin_d7 = Y9_GPIO_NUM;
28 config.pin_xclk = XCLK_GPIO_NUM;
29 config.pin_pclk = PCLK_GPIO_NUM;
30 config.pin_vsync = VSYNC_GPIO_NUM;
31 config.pin_href = HREF_GPIO_NUM;
32 config.pin_sscb_sda = SIOD_GPIO_NUM;
33 config.pin_sscb_scl = SIOC_GPIO_NUM;
34 config.pin_pwdn = PWDN_GPIO_NUM;
35 config.pin_reset = RESET_GPIO_NUM;
36 config.xclk_freq_hz = 20000000;
37 config.frame_size = FRAMESIZE_UXGA;
38 config.pixel_format = PIXFORMAT_JPEG; // for streaming
39 config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
40 config.fb_location = CAMERA_FB_IN_PSRAM;
41 config.jpeg_quality = 12;
42 config.fb_count = 1;
ESP32-S3 connects to the router and prints a successful connection prompt. If it has not been successfully
connected, press the reset key on the ESP32-S3 WROOM.
69 WiFi.begin(ssid, password);
70
71 while (WiFi.status() != WL_CONNECTED) {
72 delay(500);
73 Serial.print(".");
74 }
75 Serial.println("");
76 Serial.println("WiFi connected");
Open the video streams server function of the camera and print its IP address via serial port.
78 startCameraServer();
79
80 Serial.print("Camera Ready! Use 'http://");
81 Serial.print(WiFi.localIP());
82 Serial.println("' to connect");

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 7 Camera Web Server 113

Project 7.3 Camera and SDcard

In this chapter, we continue to use the camera and SD card. We will use the onboard button as the shutter.
When the button is pressed, the ESP32-S3 takes a photo and stores the photo in the SD folder.

Component List

ESP32-S3 WROOM x1 USB cable x1 SDcard x1

Circuit

Connect Freenove ESP32-S3 to the computer using the USB cable.

Any concerns?  support@freenove.com


114 Chapter 7 Camera Web Server www.freenove.com █

Sketch

This code uses a library named "Freenove_WS2812_Lib_for_ESP32", if you have not installed it, please do so
first.
Library is an important feature of the open source world, and we know that Arduino is an open source platform
that everyone can contribute to. Libraries are generally licensed under the LGPL, which means you can use
them for free to apply to your creations.
How to install the library
There are two ways to add libraries.
The first way, open the Arduino IDE, click Sketch  Include Library  Manager Libraries.

In the pop-up window, Library Manager, search for the name of the Library, “Freenove WS2812 Lib for ESP32”.
Then click Install.

The second way,open Arduino IDE,click SketchInclude LibraryAdd .ZIP Library,In the pop-up window,
find the file named “./Libraries/Freenove_WS2812_Lib_for_ESP32.Zip” which locates in this directory,and
click OPEN.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 7 Camera Web Server 115

Sketch_07.3_Camera_SDcard

Compile and upload the code to the ESP32-S3.


If your camera is not installed properly, causing the camera to fail to initialize, or you have not inserted the
SD card into the ESP32-S3 in advance, the on-board colored lights will turn on red as a reminder. If all is well,
the onboard colored light will light up green. When the onboard BOOT button is pressed, the ESP32-S3 will
capture the current camera image and save it in the "Camera" folder of the SD card. At the same time, the
onboard LED lights up blue, and returns to green after taking a photo.

Any concerns?  support@freenove.com


116 Chapter 7 Camera Web Server www.freenove.com █

As shown in the image below, after uploading the code to the ESP32-S3, the ESP32-S3 will automatically
create a folder named "camera" in the SD card. Every time the BOOT button is pressed, the on-board colored
light turns on blue, and ESP32-S3 collects a photo information and stores it in the "camera" folder. Press the
button once to take a photo.
When we press the RST button to reset the ESP32-S3, we can see that there are some photo files in the SD
card folder. These photos you can read directly through the card reader.

The SD card information when press RST button.

The information when press BOOT


button to takge a picture.

Information when click RST button again.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 7 Camera Web Server 117

The following is the main program code. You need include other code files in the same folder when write
your own code.
1 #include "esp_camera.h"
2 #define CAMERA_MODEL_ESP32S3_EYE
3 #include "camera_pins.h"
4 #include "ws2812.h"
5 #include "sd_read_write.h"
6
7 #define BUTTON_PIN 0
8
9 void setup() {
10 Serial.begin(115200);
11 Serial.setDebugOutput(false);
12 Serial.println();
13 pinMode(BUTTON_PIN, INPUT_PULLUP);
14 ws2812Init();
15 sdmmcInit();
16 //removeDir(SD_MMC, "/camera");
17 createDir(SD_MMC, "/camera");
18 listDir(SD_MMC, "/camera", 0);
19 if(cameraSetup()==1){
20 ws2812SetColor(2);
21 }
22 else{
23 ws2812SetColor(1);
24 return;
25 }
26 }
27
28 void loop() {
29 if(digitalRead(BUTTON_PIN)==LOW){
30 delay(20);
31 if(digitalRead(BUTTON_PIN)==LOW){
32 ws2812SetColor(3);
33 while(digitalRead(BUTTON_PIN)==LOW);
34 camera_fb_t * fb = NULL;
35 fb = esp_camera_fb_get();
36 if (fb != NULL) {
37 int photo_index = readFileNum(SD_MMC, "/camera");
38 if(photo_index!=-1)
39 {
40 String path = "/camera/" + String(photo_index) +".jpg";
41 writejpg(SD_MMC, path.c_str(), fb->buf, fb->len);
42 }

Any concerns?  support@freenove.com


118 Chapter 7 Camera Web Server www.freenove.com █

43 esp_camera_fb_return(fb);
44 }
45 else {
46 Serial.println("Camera capture failed.");
47 }
48 ws2812SetColor(2);
49 }
50 }
51 }
52
53 int cameraSetup(void) {
54 camera_config_t config;
55 config.ledc_channel = LEDC_CHANNEL_0;
56 config.ledc_timer = LEDC_TIMER_0;
57 config.pin_d0 = Y2_GPIO_NUM;
58 config.pin_d1 = Y3_GPIO_NUM;
59 config.pin_d2 = Y4_GPIO_NUM;
60 config.pin_d3 = Y5_GPIO_NUM;
61 config.pin_d4 = Y6_GPIO_NUM;
62 config.pin_d5 = Y7_GPIO_NUM;
63 config.pin_d6 = Y8_GPIO_NUM;
64 config.pin_d7 = Y9_GPIO_NUM;
65 config.pin_xclk = XCLK_GPIO_NUM;
66 config.pin_pclk = PCLK_GPIO_NUM;
67 config.pin_vsync = VSYNC_GPIO_NUM;
68 config.pin_href = HREF_GPIO_NUM;
69 config.pin_sscb_sda = SIOD_GPIO_NUM;
70 config.pin_sscb_scl = SIOC_GPIO_NUM;
71 config.pin_pwdn = PWDN_GPIO_NUM;
72 config.pin_reset = RESET_GPIO_NUM;
73 config.xclk_freq_hz = 20000000;
74 config.frame_size = FRAMESIZE_UXGA;
75 config.pixel_format = PIXFORMAT_JPEG; // for streaming
76 config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
77 config.fb_location = CAMERA_FB_IN_PSRAM;
78 config.jpeg_quality = 12;
79 config.fb_count = 1;
80
81 // if PSRAM IC present, init with UXGA resolution and higher JPEG quality
82 // for larger pre-allocated frame buffer.
83 if(psramFound()){
84 config.jpeg_quality = 10;
85 config.fb_count = 2;
86 config.grab_mode = CAMERA_GRAB_LATEST;

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 7 Camera Web Server 119

87 } else {
88 // Limit the frame size when PSRAM is not available
89 config.frame_size = FRAMESIZE_SVGA;
90 config.fb_location = CAMERA_FB_IN_DRAM;
91 }
92
93 // camera init
94 esp_err_t err = esp_camera_init(&config);
95 if (err != ESP_OK) {
96 Serial.printf("Camera init failed with error 0x%x", err);
97 return 0;
98 }
99
100 sensor_t * s = esp_camera_sensor_get();
101 // initial sensors are flipped vertically and colors are a bit saturated
102 s->set_vflip(s, 1); // flip it back
103 s->set_brightness(s, 1); // up the brightness just a bit
104 s->set_saturation(s, 0); // lower the saturation
105
106 Serial.println("Camera configuration complete!");
107 return 1;
108 }
Configure camera parameters, including camera interface pins and other information. Altering them is
generally not recommended. Returns 1 if the camera is initialized successfully, and returns 0 if it fails.
53 int cameraSetup(void) {
54 camera_config_t config;
55 config.ledc_channel = LEDC_CHANNEL_0;
56 config.ledc_timer = LEDC_TIMER_0;
57 config.pin_d0 = Y2_GPIO_NUM;
58 config.pin_d1 = Y3_GPIO_NUM;
59 config.pin_d2 = Y4_GPIO_NUM;
60 config.pin_d3 = Y5_GPIO_NUM;
61 config.pin_d4 = Y6_GPIO_NUM;
62 config.pin_d5 = Y7_GPIO_NUM;
63 config.pin_d6 = Y8_GPIO_NUM;
64 config.pin_d7 = Y9_GPIO_NUM;
65 config.pin_xclk = XCLK_GPIO_NUM;
66 config.pin_pclk = PCLK_GPIO_NUM;
67 config.pin_vsync = VSYNC_GPIO_NUM;
68 config.pin_href = HREF_GPIO_NUM;
69 config.pin_sscb_sda = SIOD_GPIO_NUM;
70 config.pin_sscb_scl = SIOC_GPIO_NUM;
71 config.pin_pwdn = PWDN_GPIO_NUM;
72 config.pin_reset = RESET_GPIO_NUM;

Any concerns?  support@freenove.com


120 Chapter 7 Camera Web Server www.freenove.com █

73 config.xclk_freq_hz = 20000000;
74 config.frame_size = FRAMESIZE_UXGA;
75 config.pixel_format = PIXFORMAT_JPEG; // for streaming
76 config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
77 config.fb_location = CAMERA_FB_IN_PSRAM;
78 config.jpeg_quality = 12;
79 config.fb_count = 1;
80
81 // if PSRAM IC present, init with UXGA resolution and higher JPEG quality
82 // for larger pre-allocated frame buffer.
83 if(psramFound()){
84 config.jpeg_quality = 10;
85 config.fb_count = 2;
86 config.grab_mode = CAMERA_GRAB_LATEST;
87 } else {
88 // Limit the frame size when PSRAM is not available
89 config.frame_size = FRAMESIZE_SVGA;
90 config.fb_location = CAMERA_FB_IN_DRAM;
91 }
92
93 // camera init
94 esp_err_t err = esp_camera_init(&config);
95 if (err != ESP_OK) {
96 Serial.printf("Camera init failed with error 0x%x", err);
97 return 0;
98 }
99
100 sensor_t * s = esp_camera_sensor_get();
101 // initial sensors are flipped vertically and colors are a bit saturated
102 s->set_vflip(s, 1); // flip it back
103 s->set_brightness(s, 1); // up the brightness just a bit
104 s->set_saturation(s, 0); // lower the saturation
105
106 Serial.println("Camera configuration complete!");
107 return 1;
108 }

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 7 Camera Web Server 121

Initialize the serial port, buttons, lights and SD card.


10 Serial.begin(115200);
11 Serial.setDebugOutput(false);
12 Serial.println();
13 pinMode(BUTTON_PIN, INPUT_PULLUP);
14 ws2812Init();
15 sdmmcInit();
Call ws2812SetColor() to set the color of the LED. When the parameter is 0, the LED is turned off, when the
parameter is 1, the red light is displayed, when the parameter is 2, the green light is displayed, and when the
parameter is 3, the blue light is displayed.
20 ws2812SetColor(2);
Get the camera data once, then read the file number in the camera folder of the SD card, and create a new
file based on this, write the camera data into it, and finally return the camera structure pointer. If the camera
data cannot be obtained, the prompt information will be printed directly.
34 camera_fb_t * fb = NULL;
35 fb = esp_camera_fb_get();
36 if (fb != NULL) {
37 int photo_index = readFileNum(SD_MMC, "/camera");
38 if(photo_index!=-1)
39 {
40 String path = "/camera/" + String(photo_index) +".jpg";
41 writejpg(SD_MMC, path.c_str(), fb->buf, fb->len);
42 }
43 esp_camera_fb_return(fb);
44 }
45 else {
46 Serial.println("Camera capture failed.");
47 }

Any concerns?  support@freenove.com


122 Chapter 8 Camera Tcp Server www.freenove.com █

Chapter 8 Camera Tcp Server


In the previous section, we used web page to display the video data captured by ESP32-S3, and in this section,
we will use a mobile phone to display it.

Project 8.1 Camera Tcp Server

Connect ESP32-S3 using USB and check its IP address through serial monitor. Use a mobile phone to obtain
video and image data.

Component List

ESP32-S3 WROOM x1 USB cable x1

Install Freenove app

There are three ways to install app, you can choose any one.
Method 1
Use Google play to search “Freenove”, download and install.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 8 Camera Tcp Server 123

Any concerns?  support@freenove.com


124 Chapter 8 Camera Tcp Server www.freenove.com █

Method 2
Visit https://play.google.com/store/apps/details?id=com.freenove.suhayl.Freenove, and click install.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 8 Camera Tcp Server 125

Method 3
Visit https://github.com/Freenove/Freenove_app_for_Android, download the files in this library, and install
freenove.apk to your Android phone manually.

Click here to
download.

Any concerns?  support@freenove.com


126 Chapter 8 Camera Tcp Server www.freenove.com █

Menu
Open application “Freenove”, as shown below:

MENU

Device
Selection
Area

Home Page Store

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 8 Camera Tcp Server 127

Freenove 4WD Car for Raspberry Pi


In this chapter, we use Freenove 4WD Car for Raspberry Pi, so it is necessary to understand the interface of
this mode.

IP address Take photos Buzzer RGB led

Connect

Set

Control Car moving. Control camera angle and position.


Drag the middle dot to The ring in the middle is use to reset.
anywhere in the area.

Circuit

Connect Freenove ESP32-S3 to the computer using the USB cable.

Any concerns?  support@freenove.com


128 Chapter 8 Camera Tcp Server www.freenove.com █

Sketch

After making sure the Tools is configured correctly, don’t run Sketch. Due to WiFi, we need to modify Sketch
a little bit based on physical situation.

In the box in the figure above, ssid_Router and password_Router are the user's Router name and password,
which need to be modified according to the actual name and password. ssid_AP and password_AP are name
and password of a AP created by ESP32-S3, and they are freely set by the user. When all settings are correct,
compile and upload the code to ESP32-S3, turn on the serial port monitor, and set the baud rate to 115200.
The serial monitor will print out two IP addresses.

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 8 Camera Tcp Server 129

There are two methods for you to check camera data of ESP32-S3 via mobile phone APP.

Method 1:
Using your phone's WiFi function, select the WiFi name represented by ssid_AP in Sketch and enter the
password “password_AP” to connect.

Any concerns?  support@freenove.com


130 Chapter 8 Camera Tcp Server www.freenove.com █

Next, open Freenove app and select 4WD Car for Raspberry Pi mode.

Enter the IP address printed by serial port in the new interface, which generally is “192.168.4.1”

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 8 Camera Tcp Server 131

Click “Connect”.

Method 2:
Using your phone's WiFi function, select the router named ssid_Router and enter the password “ssid_password”
to connect. And then open Freenove app and select 4WD Car for Raspberry Pi mode. The operation is similar
to Method 1.

Enter the IP address printed by serial port in the new interface, which generally is not “192.168.4.1” but
another one. The IP address in this example is “192.168.1.100”. After entering the IP address, click “Connect”.

The following is the main program code. You need include other code files in the same folder when write
your own code.
Sketch_08.1_Camera_Tcp_Server
1 #include "esp_camera.h"
2 #include <WiFi.h>
3 #include <WiFiClient.h>
4 #include <WiFiAP.h>
5
6 #define CAMERA_MODEL_ESP32S3_EYE

Any concerns?  support@freenove.com


132 Chapter 8 Camera Tcp Server www.freenove.com █

7 #include "camera_pins.h"
8 #define LED_BUILT_IN 2
9
10 const char *ssid_Router = "********";
11 const char *password_Router = "********";
12 const char *ssid_AP = "********";
13 const char *password_AP = "********";
14
15 WiFiServer server_Cmd(5000);
16 WiFiServer server_Camera(8000);
17 extern TaskHandle_t loopTaskHandle;
18
19 void setup() {
20 Serial.begin(115200);
21 Serial.setDebugOutput(false);
22 Serial.println();
23 pinMode(LED_BUILT_IN, OUTPUT);
24 cameraSetup();
25
26 WiFi.softAP(ssid_AP, password_AP);
27 IPAddress myIP = WiFi.softAPIP();
28 Serial.print("AP IP address: ");
29 Serial.println(myIP);
30 server_Camera.begin(8000);
31 server_Cmd.begin(5000);
32 /////////////////////////////////////////////////////
33 WiFi.begin(ssid_Router, password_Router);
34 Serial.print("Connecting ");
35 Serial.print(ssid_Router);
36 while (WiFi.isConnected() != true) {
37 delay(500);
38 Serial.print(".");
39 //WiFi.begin(ssid_Router, password_Router);
40 }
41 Serial.println("");
42 Serial.println("WiFi connected");
43 /////////////////////////////////////////////////////
44 Serial.print("Camera Ready! Use '");
45 Serial.print(WiFi.softAPIP());
46 Serial.print(" or ");
47 Serial.print(WiFi.localIP());
48 Serial.println("' to connect in Freenove app.");
49
50 disableCore0WDT();

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 8 Camera Tcp Server 133

51 xTaskCreateUniversal(loopTask_Cmd, "loopTask_Cmd", 8192, NULL, 1, &loopTaskHandle,


0);//loopTask_Cmd uses core 0.
52 xTaskCreateUniversal(loopTask_Blink, "loopTask_Blink", 8192, NULL, 1, &loopTaskHandle,
0);//loopTask_Blink uses core 0.
53 }
54 //task loop uses core 1.
55 void loop() {
56 WiFiClient client = server_Camera.available(); // listen for incoming clients
57 if (client) { // if you get a client,
58 Serial.println("Camera Server connected to a client.");// print a message out the serial
port
59 String currentLine = ""; // make a String to hold incoming data from the client
60 while (client.connected()) { // loop while the client's connected
61 camera_fb_t * fb = NULL;
62 while (client.connected()) {
63 fb = esp_camera_fb_get();
64 if (fb != NULL) {
65 uint8_t slen[4];
66 slen[0] = fb->len >> 0;
67 slen[1] = fb->len >> 8;
68 slen[2] = fb->len >> 16;
69 slen[3] = fb->len >> 24;
70 client.write(slen, 4);
71 client.write(fb->buf, fb->len);
72 esp_camera_fb_return(fb);
73 }
74 else {
75 Serial.println("Camera Error");
76 }
77 }
78 }
79 // close the connection:
80 client.stop();
81 Serial.println("Camera Client Disconnected.");
82 }
83 }
84
85 void loopTask_Cmd(void *pvParameters) {
86 Serial.println("Task Cmd_Server is starting ... ");
87 while (1) {
88 WiFiClient client = server_Cmd.available(); // listen for incoming clients
89 if (client) { // if you get a client,
90 Serial.println("Command Server connected to a client.");// print a message out the
serial port

Any concerns?  support@freenove.com


134 Chapter 8 Camera Tcp Server www.freenove.com █

91 String currentLine = ""; // make a String to hold incoming data from the client
92 while (client.connected()) { // loop while the client's connected
93 if (client.available()) { // if there's bytes to read from the client,
94 char c = client.read(); // read a byte, then
95 client.write(c);
96 Serial.write(c); // print it out the serial monitor
97 if (c == '\n') { // if the byte is a newline character
98 currentLine = "";
99 }
100 else {
101 currentLine += c; // add it to the end of the currentLine
102 }
103 }
104 }
105 // close the connection:
106 client.stop();
107 Serial.println("Command Client Disconnected.");
108 }
109 }
110 }
111 void loopTask_Blink(void *pvParameters) {
112 Serial.println("Task Blink is starting ... ");
113 while (1) {
114 digitalWrite(LED_BUILT_IN, !digitalRead(LED_BUILT_IN));
115 delay(1000);
116 }
117 }
118
119 void cameraSetup() {
120 camera_config_t config;
121 config.ledc_channel = LEDC_CHANNEL_0;
122 config.ledc_timer = LEDC_TIMER_0;
123 config.pin_d0 = Y2_GPIO_NUM;
124 config.pin_d1 = Y3_GPIO_NUM;
125 config.pin_d2 = Y4_GPIO_NUM;
126 config.pin_d3 = Y5_GPIO_NUM;
127 config.pin_d4 = Y6_GPIO_NUM;
128 config.pin_d5 = Y7_GPIO_NUM;
129 config.pin_d6 = Y8_GPIO_NUM;
130 config.pin_d7 = Y9_GPIO_NUM;
131 config.pin_xclk = XCLK_GPIO_NUM;
132 config.pin_pclk = PCLK_GPIO_NUM;
133 config.pin_vsync = VSYNC_GPIO_NUM;
134 config.pin_href = HREF_GPIO_NUM;

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 8 Camera Tcp Server 135

135 config.pin_sscb_sda = SIOD_GPIO_NUM;


136 config.pin_sscb_scl = SIOC_GPIO_NUM;
137 config.pin_pwdn = PWDN_GPIO_NUM;
138 config.pin_reset = RESET_GPIO_NUM;
139 config.xclk_freq_hz = 20000000;
140 config.frame_size = FRAMESIZE_UXGA;
141 config.pixel_format = PIXFORMAT_JPEG; // for streaming
142 config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
143 config.fb_location = CAMERA_FB_IN_PSRAM;
144 config.jpeg_quality = 12;
145 config.fb_count = 1;
146
147 // if PSRAM IC present, init with UXGA resolution and higher JPEG quality
148 // for larger pre-allocated frame buffer.
149 if(psramFound()){
150 config.jpeg_quality = 10;
151 config.fb_count = 2;
152 config.grab_mode = CAMERA_GRAB_LATEST;
153 } else {
154 // Limit the frame size when PSRAM is not available
155 config.frame_size = FRAMESIZE_SVGA;
156 config.fb_location = CAMERA_FB_IN_DRAM;
157 }
158
159 // camera init
160 esp_err_t err = esp_camera_init(&config);
161 if (err != ESP_OK) {
162 Serial.printf("Camera init failed with error 0x%x", err);
163 return;
164 }
165
166 sensor_t * s = esp_camera_sensor_get();
167 // initial sensors are flipped vertically and colors are a bit saturated
168 s->set_vflip(s, 1); // flip it back
169 s->set_brightness(s, 1); // up the brightness just a bit
170 s->set_saturation(s, 0); // lower the saturation
171
172 Serial.println("Camera configuration complete!");
173 }
Include header files that drive camera and WiFi.
1 #include "esp_camera.h"
2 #include <WiFi.h>
3 #include <WiFiClient.h>
4 #include <WiFiAP.h>

Any concerns?  support@freenove.com


136 Chapter 8 Camera Tcp Server www.freenove.com █

5
6 #define CAMERA_MODEL_ESP32S3_EYE
7 #include "camera_pins.h"
Set name and password for router that ESP32-S3 needs to connect to. And set ESP32-S3 to open two servers,
whose port are 8000 and 5000 respectively.
10 const char *ssid_Router = "********";
11 const char *password_Router = "********";
12 const char *ssid_AP = "********";
13 const char *password_AP = "********";
Enable ESP32-S3’s server function and set two monitor ports as 5000 and 8000. In general, the two port
numbers do not require modifications.
15 WiFiServer server_Cmd(5000);
16 WiFiServer server_Camera(8000);
17 extern TaskHandle_t loopTaskHandle;
Initialize serial port, set baud rate to 115200; open the debug and output function of the serial.
20 Serial.begin(115200);
21 Serial.setDebugOutput(true);
22 Serial.println();
Define a variable for camera interface and initialize it.
119 void cameraSetup() {
120 camera_config_t config;
121 config.ledc_channel = LEDC_CHANNEL_0;
122 config.ledc_timer = LEDC_TIMER_0;
123 config.pin_d0 = Y2_GPIO_NUM;
124 config.pin_d1 = Y3_GPIO_NUM;
125 config.pin_d2 = Y4_GPIO_NUM;
126 config.pin_d3 = Y5_GPIO_NUM;
127 config.pin_d4 = Y6_GPIO_NUM;
128 config.pin_d5 = Y7_GPIO_NUM;
129 config.pin_d6 = Y8_GPIO_NUM;
130 config.pin_d7 = Y9_GPIO_NUM;
131 config.pin_xclk = XCLK_GPIO_NUM;
132 config.pin_pclk = PCLK_GPIO_NUM;
133 config.pin_vsync = VSYNC_GPIO_NUM;
134 config.pin_href = HREF_GPIO_NUM;
135 config.pin_sscb_sda = SIOD_GPIO_NUM;
136 config.pin_sscb_scl = SIOC_GPIO_NUM;
137 config.pin_pwdn = PWDN_GPIO_NUM;
138 config.pin_reset = RESET_GPIO_NUM;
139 config.xclk_freq_hz = 20000000;
140 config.frame_size = FRAMESIZE_UXGA;
141 config.pixel_format = PIXFORMAT_JPEG; // for streaming
142 config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
143 config.fb_location = CAMERA_FB_IN_PSRAM;

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 8 Camera Tcp Server 137

144 config.jpeg_quality = 12;


145 config.fb_count = 1;
146
147 // if PSRAM IC present, init with UXGA resolution and higher JPEG quality
148 // for larger pre-allocated frame buffer.
149 if(psramFound()){
150 config.jpeg_quality = 10;
151 config.fb_count = 2;
152 config.grab_mode = CAMERA_GRAB_LATEST;
153 } else {
154 // Limit the frame size when PSRAM is not available
155 config.frame_size = FRAMESIZE_SVGA;
156 config.fb_location = CAMERA_FB_IN_DRAM;
157 }
158
159 // camera init
160 esp_err_t err = esp_camera_init(&config);
161 if (err != ESP_OK) {
162 Serial.printf("Camera init failed with error 0x%x", err);
163 return;
164 }
165
166 sensor_t * s = esp_camera_sensor_get();
167 // initial sensors are flipped vertically and colors are a bit saturated
168 s->set_vflip(s, 1); // flip it back
169 s->set_brightness(s, 1); // up the brightness just a bit
170 s->set_saturation(s, 0); // lower the saturation
171
172 Serial.println("Camera configuration complete!");
173 }
Loop function will constantly send camera data obtained to mobile phone APP.
60 while (client.connected()) {
61 fb = esp_camera_fb_get();
62 if (fb != NULL) {
63 uint8_t slen[4];
64 slen[0] = fb->len >> 0;
65 slen[1] = fb->len >> 8;
66 slen[2] = fb->len >> 16;
67 slen[3] = fb->len >> 24;
68 client.write(slen, 4);
69 client.write(fb->buf, fb->len);
70 esp_camera_fb_return(fb);
71 }
72 else {

Any concerns?  support@freenove.com


138 Chapter 8 Camera Tcp Server www.freenove.com █

73 Serial.println("Camera Error");
74 }
75 }
The loopTask_Cmd() function sends the received instruction back to the phone app and prints it out through
a serial port.
85 void loopTask_Cmd(void *pvParameters) {
86 Serial.println("Task Cmd_Server is starting ... ");
87 while (1) {
88 WiFiClient client = server_Cmd.available(); // listen for incoming clients
89 if (client) { // if you get a client,
90 Serial.println("Command Server connected to a client.");// print a message out the
serial port
91 String currentLine = ""; // make a String to hold incoming data from the client
92 while (client.connected()) { // loop while the client's connected
93 if (client.available()) { // if there's bytes to read from the client,
94 char c = client.read(); // read a byte, then
95 client.write(c);
96 Serial.write(c); // print it out the serial monitor
97 if (c == '\n') { // if the byte is a newline character
98 currentLine = "";
99 }
100 else {
101 currentLine += c; // add it to the end of the currentLine
102 }
103 }
104 }
105 // close the connection:
106 client.stop();
107 Serial.println("Command Client Disconnected.");
108 }
109 }
110 }
loopTask_ Blink()function will control the blinking of LED. When you see LED blinking, it indicates that ESP32-
S3 has been configured and starts working.
112 void loopTask_Blink(void *pvParameters) {
113 Serial.println("Task Blink is starting ... ");
114 while (1) {
115 digitalWrite(LED_BUILT_IN, !digitalRead(LED_BUILT_IN));
116 delay(1000);
117 }
118 }

Any concerns?  support@freenove.com


█ www.freenove.com Chapter 8 Camera Tcp Server 139

If you do not have a router near you, or if you are outdoors, you can annotate the following code, and then
compile and upload it to ESP32-S3. And you can display the video images on your phone by Method 1.
32 /////////////////////////////////////////////////////
33 WiFi.begin(ssid_Router, password_Router);
34 Serial.print("Connecting ");
35 Serial.print(ssid_Router);
36 while (WiFi.status() != WL_CONNECTED) {
37 delay(500);
38 Serial.print(".");
39 WiFi.begin(ssid_Router, password_Router);
40 }
41 Serial.println("");
42 Serial.println("WiFi connected");
43 /////////////////////////////////////////////////////

Any concerns?  support@freenove.com


140 What’s next? www.freenove.com █

What’s next?
Thanks for your reading. This tutorial is all over here. If you find any mistakes, omissions or you have other
ideas and questions about contents of this tutorial or the kit and etc., please feel free to contact us:

support@freenove.com
We will check and correct it as soon as possible.

If you want learn more about ESP32-S3, you view our ultimate tutorial:
https://github.com/Freenove/Freenove_Ultimate_Starter_Kit_for_ESP32_S3/archive/master.zip

If you want to learn more about Arduino, Raspberry Pi, smart cars, robots and other interesting products in
science and technology, please continue to focus on our website. We will continue to launch cost-effective,
innovative and exciting products.

http://www.freenove.com/

End of the Tutorial


Thank you again for choosing Freenove products.

Any concerns?  support@freenove.com

You might also like