Lecture 3 - Introduction to ESP32
Lecture Note 3: Introduction to ESP32
- Course: CSS452 Internet of Things
- Instructor: Dr. Seksan Laitrakun
- Institution: School of ICT, SIIT, Thammasat University
Outlines
- ESP32 Specification
- Arduino IDE Setup and Uploading
- Basic Features of ESP32
- WiFi Connection
References
- Random Nerd Tutorials: https://randomnerdtutorials.com/projects-esp32/
- Last Minute Engineers: https://lastminuteengineers.com/esp32-arduino-ide-tutorial/
- Thai Easy Elect (Thai Language): https://blog.thaieasyelec.com/espino32-article-table-of-contents/
- ESP-IDF Programming Guide: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/index.html
1. ESP32 Specification
1.1 ESP32 by Thai Easy Electronics
- A feature-rich MCU with integrated Wi-Fi and Bluetooth connectivity for a wide range of applications.
![ESPino32 Board Diagram]
- Board components:
- An LED connected to Pin 16
- ESP-WROOM-32 Chip: 2.4 GHz Wi-Fi and Bluetooth Combo SoC
- The RESET button
- The PROGRAM button
- Chip CP2104: USB to serial
- LED showing the power supply 3.3 V
- The port Micro USB connected to a computer to upload an Arduino program
Analogy คิดว่า ESP32 board เป็นเหมือนคอมพิวเตอร์จิ๋ว — RESET button คือปุ่ม restart เครื่อง, PROGRAM button คือการเข้าโหมด "install" โปรแกรมใหม่ (คล้ายกด Recovery Mode), และพอร์ต USB ก็เหมือนสาย charge/data ที่เอาไว้ทั้งจ่ายไฟและส่งโค้ดเข้าไป
1.2 ESP-WROOM-32 Chip
- ESP32-WROOM-32 is a powerful, generic Wi-Fi+BT+BLE MCU module that targets a wide variety of applications.
- Specifications:
- ESP32 Dual-Core Tensilica LX6 Microcontroller 32-bit with the speed 240 MHz
- SRAM 520 KB
- Flash Memory 2 MB (16 Mbit)
- IEEE 802.11 b/g/n (frequency band: 2.4GHz)
- Bluetooth Dual Mode (Classic and BLE)
- 2.2V to 3.6V Operating Voltage
- On-Board PCB Antenna
- 32 GPIOs (3 x UARTs, 3 x SPI, 2 x I2S, 12 x ADC, 2 x DAC, 2 x I2C)
- On-Board Sensors: temperature sensor, hall sensor, capacitive touch interface
Analogy Dual-Core 240 MHz เหมือนมีพนักงานสองคนทำงานพร้อมกัน — คอร์นึงจัดการ WiFi/Bluetooth อีกคอร์นึงรันโค้ดของเรา ทำให้ทำงานได้ไม่สะดุดแม้ต้องเชื่อมต่อเน็ตไปด้วย
1.3 Pin Layout
![ESP32 Pin Layout Diagram]
- Pin types:
- Analog pins → A0 – A19
- Digital pins → GPIO
- I/O pins → both input/output
- I pins → only input
- 3V3 pins → voltage supply 3.3V
- GND pins → ground pins
1.3 Pin Functions
P1: Pin Label / Function
| Pin Label | Function |
|---|---|
| GND | Ground |
| 3V3 | 3.3 Volts |
| EN | Enable |
| A0 / 36 | ADC1_CH0 / GPIO36 |
| A3 / 39 | ADC1_CH3 / GPIO39 |
| A4 / T9 / 32 | ADC1_CH4 / TOUCH9 / GPIO32 |
| A5 / T8 / 33 | ADC1_CH5 / TOUCH8 / GPIO33 |
| A6 / 34 | ADC1_CH6 / GPIO34 |
| A7 / 35 | ADC1_CH7 / GPIO35 |
| A10 / T0 / 4 | ADC2_CH0 / TOUCH0 / GPIO4 |
P2: Pin Label / Function
| Pin Label | Function |
|---|---|
| 3V3 | 3.3 volts |
| GND | Ground |
| SCL/22 | I2C SCL / GPIO22 |
| SDA/21 | I2C SDA / GPIO21 |
| Tx | U0TXD / GPIO3 |
| Rx | U0RXD / GPIO1 |
| 17 | GPIO17 |
| 16 | GPIO16 |
| SCK / 18 | SPI SCK / GPIO18 |
| MISO / 19 | SPI MISO / GPIO19 |
P3: Pin Label / Function
| Pin Label | Function |
|---|---|
| A11 / T1 / 0 | ADC2_CH1 / TOUCH1 / GPIO0 |
| A12 / T2 / 2 | ADC2_CH2 / TOUCH2 / GPIO2 |
| A13 / T3 / 15 | ADC2_CH3 / TOUCH3 / GPIO15 |
| A14 / T4 / 13 | ADC2_CH4 / TOUCH4 / GPIO13 |
| A15 / T5 / 12 | ADC2_CH5 / TOUCH5 / GPIO12 |
| A16 / T6 / 14 | ADC2_CH6 / TOUCH6 / GPIO14 |
| A17 / T7 / 27 | ADC2_CH7 / TOUCH7 / GPIO27 |
| A18 / DAC1 / 25 | ADC2_CH8 / DAC_1 / GPIO25 |
| A19 / DAC2 / 26 | ADC2_CH9 / DAC_2 / GPIO26 |
| Vin | Vin |
P4: Pin Label / Function
| Pin Label | Function |
|---|---|
| MOSI / 23 | SPI MOSI / GPIO23 |
| SS / 5 | SPI SS / GPIO5 |
| SD2 / 9 | SD_DATA2 / GPIO9 |
| SD3 / 10 | SD_DATA3 / GPIO10 |
| CMD / 11 | SD_CMD / GPIO10 |
| CLK / 6 | SD_CLK / GPIO6 |
| SD0 / 7 | SD_DATA0 / GPIO7 |
| SD1 / 8 | SD_DATA1 / GPIO8 |
| GND | Ground |
| VBAT | VBAT |
- The microcontroller needs these pins to read data from input devices and to control output devices.
![Input Devices → ESP32 → Output Devices Diagram]
- Example input devices: PIR Motion Sensor, Button, ON-OFF Switch, Proximity Switch
- Example output devices: Relay, LED Bar Graph
1.4 ESP32 Resources
- Thai Easy Elect: https://blog.thaieasyelec.com/espino32-article-table-of-contents/
- Last Minute Engineers: https://lastminuteengineers.com/esp32-arduino-ide-tutorial/
- Random Nerd Tutorials: https://randomnerdtutorials.com/getting-started-with-esp32/
2. Arduino IDE Setup and Uploading
2.1 Arduino IDE Setup
1. Required Software: Arduino IDE
- Download from: https://www.arduino.cc/en/Main/Software
- Choose the option suitable to your computer:
![Arduino IDE Download Options Screenshot]
- For Windows OS, there are 2 choices for Arduino installation:
- Windows Installer: Arduino will automatically install all components (needs the Internet)
- Windows ZIP file: all necessary components are already in this ZIP file
2. Arduino IDE Installation by Windows ZIP File
- Unzip the file: Windows ZIP File to your computer (assume Drive C:)
- You will get a folder
arduino - To run the Arduino IDE, double click on
arduino.exein the folderarduino - If the program asks to install some components else, answer "Yes"
3. Arduino IDE Interface
![Arduino IDE Interface Screenshot]
- Interface parts:
- Menu Bar — File, Edit, Sketch, Tools, Help
- Verify Button — checks code compiles correctly
- Upload Button — uploads code to the board
- Serial Monitor button — opens the serial monitor window
- Your Arduino Code — main coding area (
setup()andloop()) - Information Window — shows compile/upload status messages
4. USB Driver
- The USB driver needed is called "CP210x USB to UART Bridge VCP driver"
- Download from: https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers?tab=downloads
- Choose a suitable version for your OS:
- CP210x Universal Windows Driver: For Windows, download and unzip this file
- In the unzipped folder, run either
CP210xVCPInstaller_x64.exeorCP210xVCPInstaller_x86(depending on your computer's platform)
- In the unzipped folder, run either
- CP210x VCP Mac OSX Driver: For Mac OS, download and install this file
- CP210x Universal Windows Driver: For Windows, download and unzip this file
5. Add ESP32 Board to Arduino IDE
-
Start the Arduino IDE by running
Arduino.exe -
On the menu bar, select: File > Preferences
-
In the "Additional Boards Manager URLs", fill in:
https://dl.espressif.com/dl/package_esp32_index.json -
Then, click "OK"
-
On the menu bar, select: Tools > Board: > Boards Manager…
-
On the board manager, fill in:
esp32 -
You will see "esp32 by Espressif Systems", select it to install
![Boards Manager Screenshot]
- Finally, on the menu bar, select Tools > Board > ThaiEasyElec's ESPino32
- Now, you are ready to program the ThaiEasyElec's ESPino32
Analogy การเพิ่ม Board URL เหมือนการเพิ่ม "app store" อีกอันให้ Arduino IDE รู้จัก — ปกติ Arduino IDE รู้จักแต่บอร์ด Arduino ทั่วไป แต่พอเราใส่ URL ของ Espressif เข้าไป มันจะไปโหลด "แพ็คเกจ" ที่ทำให้ IDE รู้จักและคุยกับบอร์ด ESP32 ได้
2.2 Uploading Your Arduino Program
- Write the following code on your Arduino IDE (this code will print "Hello World"-style counting on the serial monitor):
int a=0;
void setup() {
Serial.begin(115200);
}
void loop() {
a=a+1;
Serial.println(a);
delay(3000);
}Important The baud rate of ESP32 must be
115200 (not 9600)
- Connect ESP32 to your computer via a USB port
- On the menu bar of the Arduino IDE:
- Select Tools > Board: > ThaiEasyElect's ESPino32
- Select Tools > Port > Your_Arduino_Com_Port
- To upload your program to ESP32, click the upload icon
- On the information window (at the bottom of the Arduino IDE), whenever you see "Connecting…", you have to press the program button on the ESP32
esptool.py v2.6
Serial port COM16
Connecting........
- If uploading the program is successful, you will see "Done uploading"
- To open the serial monitor, click on the serial-monitor button
- Choose the baud rate to 115200
Analogy การกดปุ่ม PROGRAM ตอนเห็นคำว่า "Connecting..." เหมือนการกดปุ่ม "OK ฉันพร้อมรับข้อมูลแล้ว" — ESP32 กำลังรอสัญญาณเข้าสู่โหมดรับโปรแกรมใหม่ (bootloader mode) ถ้าไม่กด มันจะ timeout และ upload ไม่สำเร็จ
3. Basic Features of ESP32
3.1 Digital Inputs and Outputs
Related
1. Pins
- We can read a digital value and control a digital device via the GPIO pins
- ESP32 can read a digital input (0 or 1) and send a digital output (0 or 1) via the GPIO pins
- Each pin can be referred to in an Arduino program by its GPIO number. For example, the GPIO22 pin is referred as
22in the Arduino program
![Digital Voltage Threshold Diagram (Hysteresis)]
- Voltage thresholds:
- '1' HIGH: above 2.475V (up to 3.6V)
- Hysteresis zone: between 0.825V and 2.475V
- '0' LOW: below 0.825V (down to -0.3V)
2. Send a Digital Value to a Digital Pin
- There are 2 steps for sending:
-
Set the pin mode. Before we can use any digital pin, we have to declare the pin mode (INPUT or OUTPUT) of that pin. In general, we declare it in the
setup()function. To use a digital pin as an output pin: wherepinis the GPIO number. -
Send a digital value. To send a digital value either 0 (LOW) or 1 (HIGH) to the pin declared above: where
valueis 0 or 1 (we can also use LOW or HIGH).
- Note that:
- The value "1" means that this pin will supply the HIGH voltage (around 3.3 V)
- The value "0" means that this pin will supply the LOW voltage (around 0 V)
3. Read a Digital Value from a Digital Pin
- There are 2 steps for reading:
-
Set the pin mode. To use a digital pin as an input pin: where
pinis the GPIO number. In general, we declare it in thesetup()function -
Read a digital value. To read a digital value either 0 (LOW) or 1 (HIGH) from the pin declared above: where a digital value (0 or 1) read from this pin will be stored in a variable X.
- Note that:
- X=1 means that the input voltage to this pin is the HIGH voltage (around 3.3 V)
- X=0 means that the input voltage to this pin is the LOW voltage (around 0 V)
Analogy pinMode คือการ "ตั้งค่าประตูว่าจะให้เข้าหรือให้ออก" — เหมือนก่อนจะใช้ประตู เราต้องบอกก่อนว่าประตูนี้เป็นทางเข้า (INPUT รับสัญญาณ) หรือทางออก (OUTPUT ส่งสัญญาณ) ถ้าไม่ตั้งค่าก่อน โปรแกรมจะงงว่าประตูนี้ใช้ทำอะไร
Example 1: Button + LED
- We connect a button and an LED to ESP32 as shown below.
![Button and LED Circuit Diagram]
-
Circuit description:
- Pin 3v3 of ESP32 → 10K resistor → GPIO34 (SW) → GND when pressed (pull-up style switch)
- GPIO17 → Long leg of LED → Short leg → 330Ω resistor → GND
-
Then, we write an Arduino code to turn on/off the LED by pressing the switch:
- Press the switch → LED on
- Not press the switch → LED off
Example 1 (Digital_InOut.ino)
// set pin numbers
const int buttonPin = 34; // the push button pin
const int ledPin = 17; // the LED pin
// variable for storing the pushbutton status
int buttonState = 0;
void setup() {
Serial.begin(115200);
// initialize the pushbutton pin as an input
pinMode(buttonPin, INPUT);
// initialize the LED pin as an output
pinMode(ledPin, OUTPUT);
}
void loop() {
// read the state of the pushbutton value
buttonState = digitalRead(buttonPin);
Serial.println(buttonState);
// check if the pushbutton is pressed.
// if it is, the buttonState is LOW
if (buttonState == LOW) {
// turn LED on
digitalWrite(ledPin, HIGH);
} else {
// turn LED off
digitalWrite(ledPin, LOW);
}
}3.2 Analog Inputs
1. Pins
- We can read an equivalent analog value (voltage) from an input device connected to an analog pin (labeled as A0 – A19)
- The input voltage 0 – 3.3 volt will be mapped to the integers 0 – 4095 (the value that ESP32 will show you), where 0 is 0 volt and 4095 is 3.3 volt
2. Read an Analog Value from an Analog Pin
- To read an analog input (from an inputted device) in the ESP32 using the Arduino IDE, we use the
analogRead()function: wherepinis the name of an ESP32 analog pin (A0 – A19) and X is a variable storing a returned value between 0 – 4095.
Analogy analogRead แปลงแรงดันไฟฟ้าต่อเนื่อง (0-3.3V) เป็นตัวเลขไม่ต่อเนื่อง (0-4095) — เหมือนเอาไม้บรรทัดที่มีขีดละเอียดมาวัดแทนการกะด้วยสายตา ยิ่งค่าตัวเลขเยอะ = แรงดันไฟยิ่งสูง
Example 2: Potentiometer
- We connect a potentiometer to ESP32 as shown below.
![Potentiometer Circuit Diagram]
-
Circuit description:
- Pin 3v3 of ESP32 → Potentiometer → A0
- Pin GND of ESP32 → Potentiometer
-
Then, we write an Arduino code to read the value from this pin and show it on the serial monitor while we rotate the potentiometer.
Example 2 (Analog_In.ino)
const int potPin = A0; //Potentiometer pin
// Variable for storing the potentiometer value
int Value = 0;
void setup() {
Serial.begin(115200);
delay(1000);
}
void loop() {
// Reading potentiometer value
Value = analogRead(potPin);
Serial.println(Value);
delay(1000);
}3.3 Analog Outputs using PWM
1. Pins
- There are several methods to control an output analog device. Here, we will use the PWM method to send out (from the ESP32) an equivalent analog voltage via the PWM pins
- PWM pins: GPIO 0-19, 21-23, 25-27, 32-33
- The values sent out will be 0 – 255 which are equivalent to 0 – 3.3 volt
Analogy PWM (Pulse Width Modulation) เหมือนการกระพริบไฟเร็วมากๆ จนตาเรามองไม่ทัน — ถ้ากระพริบ "ติด" นานกว่า "ดับ" ไฟจะดูสว่างกว่า (duty cycle สูง = ค่าใกล้ 255) ถ้า "ดับ" นานกว่า ไฟจะดูสลัวกว่า (duty cycle ต่ำ = ค่าใกล้ 0) มันคือการหลอกให้ดูเหมือนแรงดันไฟ analog ทั้งที่จริงๆ เป็น digital on/off เร็วๆ
2. Send an Analog Value to a PWM Pin
- We have the following 3 steps:
Step 1: Declare these three variables at the beginning of the Arduino code
- a) Choose a PWM channel. There are 16 channels from 0 to 15
- b) Set the PWM signal frequency. For an LED, a frequency of 5000 Hz is fine to use
- c) Set the signal's duty cycle resolution. For ESP32, it is 8 since we use 8-bit resolution
int ledChannel = 0;
int freq = 5000;
int resolution = 8;Step 2: In the setup() function
- a) Declare this setup:
- b) Map the PWM pin and the PWM channel. As a result, the PWM signal will be sent to this PWM pin: where
PWMpinis the GPIO number of a PWM pin andchannelis the variable defined in Step 1.
Step 3: Send a PWM signal to the PWM pin
- Control the channel by using the following function: where
channelis the variable defined in Step 1 and the duty cycle is a value between 0 – 255 (0 is 0 volt and 255 is 3.3 volt).
Example 3: Potentiometer + LED Brightness
- We connect a potentiometer and an LED to ESP32 as shown below.
![Potentiometer and LED PWM Circuit Diagram]
-
Circuit description:
- Pin 3v3 of ESP32 → Potentiometer → A0
- Pin GND of ESP32 → Potentiometer
- GPIO17 → Long leg of LED → Short leg → 330Ω resistor → GND
-
Then, we write an Arduino code such that we can adjust the brightness of the LED by rotating the potentiometer.
Example 3 (Analog_PWM.ino)
const int potPin = A0; //Potentiometer pin
const int ledPin = 17; // LED pin
// setting PWM properties --- Step 1: Declare variables
const int freq = 5000;
const int ledChannel = 0;
const int resolution = 8;
// Variable for storing the potentiometer value
int potValue = 0;
int ledValue = 0;
void setup() { // Step 2: Set up
// configure LED PWM functionalitites
ledcSetup(ledChannel, freq, resolution);
// attach the channel to the GPIO to be controlled
ledcAttachPin(ledPin, ledChannel);
}
void loop() {
// Reading potentiometer value
potValue = analogRead(potPin);
ledValue = map(potValue, 0, 4095, 0, 255);
// changing the LED brightness with PWM --- Step 3: Send the command
ledcWrite(ledChannel, ledValue);
}3.4 Built-in Touch Sensors
Related
1. Pins
- The ESP32 has 10 capacitive touch GPIOs. These GPIOs can sense variations in anything that holds an electrical charge, like human skin, so they can detect variations induced when touching a GPIO pin with a finger
- These pins are the following GPIO pins: 0, 2, 4, 12, 13, 14, 15, 27, 32, 33
2. Command to Read from a Touch Sensor
- To read a value from a touch-sensor pin: where
pinis the GPIO number of a touch-sensor pin and X stores an integer between 0 and 1023 returned from this command.- When no one touches this pin, a high value will be returned
- When we touch this pin, a low value will be returned
Analogy touchRead ทำงานตรงข้ามกับที่คิด — ปกติเราคิดว่าแตะ = ค่าสูง แต่จริงๆ แตะ = ค่าต่ำ เพราะร่างกายเราไปดูดประจุไฟฟ้าออกจากพื้นผิวสัมผัส (คล้ายจับมือแล้วดูดความร้อนออกจากมืออีกฝ่าย)
Example 4: Touch Sensor
- We connect a wire to the pin GPIO32 (a touch-sensor pin) of ESP32 as shown below.
![Wire Connected to GPIO32 Touch Sensor Photo]
- Then, we write an Arduino code to read the value from this pin and show it on the serial monitor, every 1 second.
Example 4 (Touch_Pin.ino)
void setup() {
Serial.begin(115200);
delay(1000); // give me time to bring up serial monitor
Serial.println("ESP32 Touch Test");
}
void loop() {
Serial.println(touchRead(32)); // Touch sensor from Pin 32
delay(1000);
}- The values given from the touch sensor when we touch the wire will drop noticeably (e.g. from ~38 down to single digits like 6-9).
3.5 Built-in Hall Effect Sensor
- The ESP32 features a built-in hall effect sensor which is located behind the metal cap
- A hall effect sensor can detect variations in the magnetic field in its surroundings. The greater the magnetic field, the greater the output voltage
![ESP32 Board Showing Hall Sensor Location]
- To read the value from the Hall sensor: where X stores a returned integer between -500 and 500 from the built-in Hall sensor.
Analogy Hall sensor เหมือน "จมูกที่ดมกลิ่นสนามแม่เหล็ก" — ยิ่งเอาแม่เหล็กเข้าใกล้ ค่าที่อ่านได้ยิ่งเปลี่ยนแปลงมาก (บวกหรือลบขึ้นกับขั้วแม่เหล็ก) เหมือนเข็มทิศที่ขยับตามสนามแม่เหล็กรอบตัว
Example 5: Hall Effect Sensor
Example 5 (Hall_Effect.ino)
void setup() {
Serial.begin(115200);
delay(1000); // give me time to bring up serial monitor
Serial.println("ESP32 Hall Effect Test");
}
void loop() {
Serial.println(hallRead()); // Read the hall effect
delay(1000);
}- Using the code here, ESP32 will read a value from the hall-effect sensor and show it on the serial monitor, every 1 second.
3.6 A Software Reset
- We can use the following command to restart the Arduino program in ESP32:
Code example (Soft_Reset.ino) — ESP32 will restart every 10 seconds:
void setup() {
Serial.begin(115200);
Serial.println("Restarting in 10 seconds");
delay(10000);
ESP.restart();
}
void loop() {
}4. WiFi Connection
Related
4.1 Roles of ESP32 in a WiFi Network
- ESP32 has a WiFi module which can communicate via a WiFi network. It can be set up as:
- a web client
- a web server
- a local access point
![ESP32 Client / Server / Soft Access Point Diagrams]
Analogy คิดง่ายๆ แบบร้านอาหาร:
- Client mode = ESP32 เป็นลูกค้าที่เดินเข้าไปสั่งของจากร้าน (router/internet)
- Server mode = ESP32 เป็นร้านที่รอรับออเดอร์จากลูกค้า (มือถือ/PC)
- Soft Access Point mode = ESP32 เปิดร้านของตัวเอง ไม่ต้องพึ่ง router ใครมาก็เชื่อมต่อกับ ESP32 ได้โดยตรง
4.2 Commands to Connect to a WiFi Network
-
To connect WiFi by using ESP32, we need to include the header file "WiFi.h":
#include <WiFi.h> -
Commands to set up and connect to a WiFi network:
| Function | Explanation |
|---|---|
WiFi.begin("ssid", "password") | ESP32 will try to connect to the access point ssid by using the password password (the password of this SSID) |
WiFi.localIP() | This function returns ESP32's IP address |
WiFi.mode(WIFI_STA) | Let this ESP32 work as a (WiFi) station |
WiFi.status() | This function returns codes describing the Wi-Fi connection status: • 0 : WL_IDLE_STATUS — Wi-Fi is in process of changing between statuses • 1 : WL_NO_SSID_AVAIL — configured SSID cannot be reached • 3 : WL_CONNECTED — successful connection is established • 4 : WL_CONNECT_FAILED — password is incorrect • 6 : WL_DISCONNECTED — module is not configured in station mode |
Example 6: Connect to WiFi
Example 6 (WiFi_Connection.ino)
#include <WiFi.h> // The header file to connect to WiFi
void setup() {
Serial.begin(115200); // Baud rate = 115200
Serial.println();
WiFi.mode(WIFI_STA); // Set the ESP32 in a station mode
WiFi.begin("Your_SSID", "Your_Password"); // Connect to SSID "Your_SSID" using password "Your_Password"
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) { // ESP32 is trying to connect to the SSID
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP()); // Show the ESP32's IP address on the serial monitor
}
void loop() {
}-
Results shown on the serial monitor:
Connecting............Connected, IP address: 10.1.10.30
4.3 Commands to Set up as a Local Access Point
-
To set up ESP32 as a local access point, we need to include the header file "WiFi.h":
#include <WiFi.h> -
Commands to set up ESP32 as a local access point:
| Function | Explanation |
|---|---|
WiFi.softAP("ssid", "password", channel, hidden) | • ssid - character string containing network SSID (max. 63 characters)• password - optional character string with a password. For WPA2-PSK network it should be at least 8 characters long. If not specified, the access point will be open for anybody to connect• channel - optional parameter to set Wi-Fi channel, from 1 to 13. Default channel = 1• hidden - optional parameter, if set to true will hide SSID |
WiFi.softAPgetStationNum() | This function returns the number of stations connecting to ESP32 (which is now an access point) |
Example 7: Local Access Point
-
The following code will set up ESP32 as a local access point and show the number of stations connecting to it. After uploading this code, ESP32 will work as a local access point and we can use our mobile phone to connect to it.
-
Key commands:
WiFi.softAP("Your_SSID", "Your_Password");→ To set ESP32 as an access point with SSID "Your_SSID" and password "Your_Password"
Example 7 (WiFi_SoftAccessPoint.ino)
#include <WiFi.h>
void setup() {
Serial.begin(115200);
Serial.println();
Serial.print("Setting soft-AP ... ");
// Set this ESP32 as an access point named Your_SSID with the password Your_Password
boolean result = WiFi.softAP("Your_SSID", "Your_Password");
if(result == true) {
Serial.println("Ready");
} else {
Serial.println("Failed!");
}
}
void loop() {
// Return the number of stations connecting to this access point
Serial.printf("Stations connected = %d\n", WiFi.softAPgetStationNum());
delay(3000);
}4.4 Getting Date and Time from an NTP Server
1. Introduction
- Getting date and time is especially useful in data logging to timestamp our readings
- If ESP32 can access the Internet, we can get date and time using Network Time Protocol (NTP), and we do not need additional hardware (like an RTC clock)
- There are NTP servers like
pool.ntp.orgthat anyone can use to request time as a client - The ESP32 acts as an NTP Client that requests time from an NTP Server (
pool.ntp.org)
![ESP32 → Router → Internet → NTP Server Request/Receive Time Diagram]
Example 8: NTP Date/Time
Example 8 (DateTimerNTP.ino)
#include <WiFi.h>
#include "time.h"
const char* ssid = "Your_SSID";
const char* password = "Your_Password";
const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 7*3600;
const int daylightOffset_sec = 0;
void printLocalTime() {
struct tm timeinfo;
if(!getLocalTime(&timeinfo)){
Serial.println("Failed to obtain time");
return;
}
Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}
void setup() {
Serial.begin(115200);
//connect to WiFi
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" CONNECTED");
//init and get the time
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
printLocalTime();
//disconnect WiFi as it's no longer needed
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
}
void loop() {
delay(1000);
printLocalTime();
}-
The current date and time are shown on the serial monitor, e.g.:
Connecting to MyWiFi ..... CONNECTEDSunday, August 01 2021 10:38:35Sunday, August 01 2021 10:38:36Sunday, August 01 2021 10:38:37...
Explanations
-
Once ESP32 is connected to the network, we initialize the NTP client using the
configTime()function to get date and time from an NTP server://init and get the time configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);- This function needs three input parameters, which have been defined earlier:
const char* ntpServer = "pool.ntp.org"; const long gmtOffset_sec = 7*3600; const int daylightOffset_sec = 0;- where
ntpServeris the URL of an NTP server,gmtOffset_secis the UTC offset for our time zone in seconds (Thailand is +7 hours), anddaylightOffsetis the Daylight saving time (0 for Thailand).
-
The
printLocalTime()custom function prints the current date & time:void printLocalTime() { struct tm timeinfo; if(!getLocalTime(&timeinfo)){ Serial.println("Failed to obtain time"); return; } Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); }- The
getLocalTime()function gets date and time from the NTP server and stores them in the variabletimeinfo - It prints the received date and time stored in
timeinfointo a readable format where:
- The
| Format Specifier | Meaning |
|---|---|
%A | returns day of week |
%B | returns month of year |
%d | returns day of month |
%Y | returns year |
%H | returns hour |
%M | returns minutes |
%S | returns seconds |
Remark
-
We connect to the NTP server only one time at the beginning. The time later is counted by the internal clock.
-
If we want to store date or time in a variable, we use the
strftime()function.- Example: copy the hour from
timeinfointotimeHour(declared to store up to 3 characters: 2 for two-digit numbers and 1 for the terminating character):
char timeHour[3]; strftime(timeHour,3, "%H", &timeinfo); Serial.println(timeHour);- Example: for the week day, create a char variable with a length of 10 characters because the longest day of the week contains 9 characters (Saturday):
char timeWeekDay[10]; strftime(timeWeekDay,10, "%A", &timeinfo); Serial.println(timeWeekDay); Serial.println(); - Example: copy the hour from
-
More explanations: https://randomnerdtutorials.com/esp32-date-time-ntp-client-server-arduino/
-
In addition, we can write an Arduino code to get Epoch/Unix Time. The Epoch Time (also known as Unix epoch, Unix time, POSIX time, or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970. Code example: https://randomnerdtutorials.com/epoch-unix-time-esp32-arduino/
5. Advanced Topics to Explore More
5. ESP32 Over-The-Air (OTA) Updates
1. What is OTA?
- Wireless Programming: Replaces physical USB cables entirely, enabling code deployment over Wi-Fi networks
2. Practical Usage
- Sealed Enclosures: Update waterproof, ruggedized, or industrial hardware shells without breaking gaskets
- Remote IoT Nodes: Maintain ceiling, roof, or field-mounted setups without physically extracting the board
3. Library and Requirements
- Core Library: Built directly on the standard
ArduinoOTA.hframework for seamless IDE network port mapping - Non-Blocking Loop: Requires a fluid loop architecture — traditional blocking
delay()functions must be replaced withmillis()
Analogy OTA เหมือนการอัปเดตแอปบนมือถือแบบไม่ต้องเสียบสาย — ปกติเวลาจะเปลี่ยนโค้ดใน ESP32 ต้องเสียบ USB ใหม่ แต่ OTA ทำให้ส่งโค้ดผ่าน WiFi ได้เลย มีประโยชน์มากถ้าอุปกรณ์ถูกติดตั้งในที่เข้าถึงยาก เช่น ติดเพดานหรือกันน้ำปิดสนิท
5. More Sensors and Actuators
- ESP32 can connect to many sensors and actuators:
- Temperature and Humidity Sensor: https://randomnerdtutorials.com/esp32-dht11-dht22-temperature-humidity-sensor-arduino-ide/
- MPU-6050 Accelerometer and Gyroscope: https://randomnerdtutorials.com/esp32-mpu-6050-accelerometer-gyroscope-arduino/
- OLED Display: https://randomnerdtutorials.com/esp32-ssd1306-oled-display-arduino-ide/
- Etc.
Linked from
- 07 - AVR Timer + Counter Programming
- 10 - AVR Serial Port and ADC Programming in C
- 11 - Arduino UNO Programming using Arduino IDE
- 12 - Arduino UNO Programming - Digital and Analog Interfaces
- Lecture 4 - Transmission Media
- Lecture 13 - Wireless Network & Firewall
- Lecture 1 - Introduction to IoT
- Lecture 2 - IoT Architectures & a Use Case
- Lecture 4 - ESP32 – Multitasking and Deep Sleep
- Lecture 5 - Web Servers and Clients
- Lecture 6 - MQTT Clients