Skip to content

5. Arduino C Tutorial

Project 01 Hello World

1. Project Introduction:

For ESP32 beginners, we will start with something simple. In this project, you only need an ESP32 board, a USB cable, and a computer to complete the "Hello World!" project. It is not only a communication test between the ESP32 board and the computer, but also a beginner-level project for ESP32.

2. Project Components:

图片不存在 图片不存在
ESP32*1 USB Cable*1

3. Project Wiring:

In this project, we connect the ESP32 to the computer via a USB cable.

图片不存在

4. Project Code:

You can open the code we provided. The code used in this project is saved in (i.e., the path): ..\program-code\arduino-c-windows-code. (The path for the project code below is the same, i.e.: same as below.)

//*************************************************************************************
/*
 * File name : Hello World
 * Description: Enter the letter R and the serial port displays "Hello World".
 */
char val;// Define variable val
void setup()
{
Serial.begin(115200);// Set baud rate to 115200
}
void loop()
{
  if (Serial.available() > 0) {
    val=Serial.read();// Read and assign to val
    if(val=='R')// Check for input letter "R"
    {  // If so,
     Serial.println("Hello World!");// Display "Hello World !".
    }
  }
}
//*************************************************************************************
Before uploading the project code to the ESP32, click "Tools" → "Board" and select "ESP32 Wrover Module". (The steps for uploading project code below are the same, i.e.: same as below.)

图片不存在

Select the correct port (COM). (Note: You can only see the corresponding port after connecting the ESP32 board to the computer via a USB cable.)

图片不存在

Note: For macOS users, if uploading fails, set the baud rate to 115200 before clicking.

图片不存在

Click 图片不存在 to upload the project code to the ESP32 board.

图片不存在

Note: If the code upload is unsuccessful, click 图片不存在 again and press and hold the Boot button 图片不存在 on the ESP32 board with your hand. Release the Boot button after the upload progress percentage appears, as shown below:

图片不存在

Project code uploaded successfully!

图片不存在

5. Project Result:

After the project code is uploaded successfully, click the icon 图片不存在 to enter the serial monitor, set the baud rate to 115200, enter the letter "R" in the text box, and press the Enter key. The serial monitor will print "Hello World!".

图片不存在

Project 02 Light Up LED

1. Project Introduction:

In this project, we will show you how to light up an LED. We use a digital pin of the ESP32 to turn on the LED, causing it to light up.

2. Project Components:

图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Red LED*1
图片不存在 图片不存在 图片不存在
220Ω Resistor*1 Jumper Wires*2 USB Cable*1

3. Component Knowledge:

(1) LED

图片不存在

An LED is a semiconductor called a "Light Emitting Diode," an electronic device made of semiconductor materials (silicon, selenium, germanium, etc.). It has a positive and a negative terminal. The short leg is the negative terminal, connecting to GND; the long leg is the positive terminal, connecting to 3.3V or 5V.

图片不存在

(2) Five-Color Band Resistor

A resistor is an electronic component that limits or regulates the flow of current in a circuit. On the left is the appearance of a resistor, and on the right is the symbol for a resistor in a circuit. The unit of resistance (R) is the ohm (Ω). 1 MΩ = 1000 kΩ, 1 kΩ = 1000Ω.

We can use resistors to protect sensitive components such as LEDs. The resistance value (in Ω) is marked on the body of the resistor with small color bands. Each color represents a number, which you can look up using a resistor color code chart.

图片不存在

In this kit, we provide 3 five-color band resistors with different resistance values. Here are 3 examples:

220Ω Resistor×10

图片不存在

10KΩ Resistor×10

图片不存在

1KΩ Resistor×10

图片不存在

Under the same voltage, there will be a smaller current and a larger resistance. The relationship between current, voltage, and resistance can be expressed by the formula: I=U/R. In the figure below, the current through R1: I = U / R = 3V / 10KΩ = 0.0003A = 0.3mA.

图片不存在

Do not connect a resistor with a very low resistance value directly across the power supply terminals, as this will cause excessive current and damage electronic components. Resistors do not have positive or negative polarity.

(3) Breadboard

A breadboard is an important tool used in laboratories for prototyping circuits. It has many holes for inserting integrated circuits, resistors, and other circuit components. Mastering the use of a breadboard is essential for improving experimental efficiency and reducing the chance of experimental failures. Below is a brief introduction to the structure and usage of a breadboard. A typical breadboard is shown below:

图片不存在

The appearance and internal structure of a breadboard are shown above. A common minimal-unit breadboard consists of three parts: top, middle, and bottom. The top and bottom parts are usually narrow strips consisting of one or two rows of holes, while the middle part is a strip consisting of a central isolation groove and five rows of holes above and below it.

图片不存在

The two narrow strips on the breadboard each have two rows of holes. The two rows are not connected to each other and are generally used as power supply paths. The first row on top, marked with "+", has 10 groups of holes (all internally connected), serving as the positive rail; the second row on top, marked with "-", has 10 groups of holes (all internally connected), serving as the ground rail. The first and second rows at the bottom of the breadboard have the same structure. If you need to use the entire breadboard, usually connect "+" to "+" and "-" to "-" with wires.

The middle wide strip consists of a central isolation groove and five rows of holes above and below it. The 5 holes in the same column are connected to each other, while columns and the areas above and below the groove are not connected. The appearance and structure are shown below:

图片不存在

The connection holes in the middle wide strip are divided into upper and lower sections. This is the main working area of the breadboard, used for inserting components and jumper wires. The 5 holes in the same column (i.e., a-b-c-d-e, f-g-h-i-j) are connected to each other, while columns and the areas above and below the groove are not connected. When doing experiments, a small unit consisting of two narrow strips and one wide strip is usually used. The main part of the circuit is built on the wide strip, one row of the top narrow strip is used for power, and one row of the bottom narrow strip is used for ground. The middle wide strip is used to connect the circuit. Since the groove is not connected above and below, integrated circuits are generally inserted across the groove.

(4) Power Supply

The ESP32 requires a 3.3V-5V power supply. In this project, we connect the ESP32 to the computer using a USB cable.

图片不存在

4. Project Wiring Diagram:

First, turn off all power to the ESP32. Then build the circuit according to the wiring diagram. After the circuit is built and verified, connect the ESP32 to the computer using a USB cable.

Note: Avoid any possible short circuits (especially between 3.3V and GND)!

Warning: Short circuits can cause large currents in the circuit, leading to overheating of components and permanent damage to the hardware.

图片不存在

Note:

How to connect an LED

图片不存在

How to identify a five-color band 220Ω resistor

图片不存在

5. Project Code:

You can open the code we provided. The code used in this project is saved in (i.e., the path): ..\program-code\arduino-c-windows-code. (The path for the project code below is the same, i.e.: same as below.)

//**********************************************************************
/*
 * File name : Light Up LED
 * Description: Light up a lamp.
 */
#define LED_BUILTIN 15

// The setup function runs only once when reset or powered on
void setup() {
  // Initialize the digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // Turn on the LED (HIGH is high level)
}
//*************************************************************************************
Before uploading the project code to the ESP32, click "Tools" → "Board" and select "ESP32 Wrover Module". (The steps for uploading project code below are the same, i.e.: same as below.)

图片不存在

Select the correct port (COM). (Note: You can only see the corresponding port after connecting the ESP32 board to the computer via a USB cable.)

图片不存在

Note: For macOS users, if uploading fails, set the baud rate to 115200 before clicking.

图片不存在

Click 图片不存在 to upload the project code to the ESP32 board.

图片不存在

Note: If the code upload is unsuccessful, click 图片不存在 again and press and hold the Boot button 图片不存在 on the ESP32 board with your hand. Release the Boot button after the upload progress percentage appears, as shown below:

图片不存在

Project code uploaded successfully!

图片不存在

6. Project Phenomenon:

After the project code is uploaded successfully, power it via the USB cable, and the LED will light up.

图片不存在

Project 03 LED Blinking

1. Project Introduction:

In this project, we will show you the LED blinking effect. We use a digital pin of the ESP32 to turn on the LED and make it blink.

2. Project Components:

图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Red LED*1
图片不存在 图片不存在 图片不存在
220Ω Resistor*1 Jumper Wires*2 USB Cable*1

3. Project Wiring Diagram:

First, turn off all power to the ESP32. Then build the circuit according to the schematic and wiring diagram. After the circuit is built and verified, connect the ESP32 to the computer using a USB cable.

Note: Avoid any possible short circuits (especially between 3.3V and GND)!

Warning: Short circuits can cause large currents in the circuit, leading to overheating of components and permanent damage to the hardware.

图片不存在

Note:

How to connect an LED

图片不存在

How to identify a five-color band 220Ω resistor

图片不存在

4. Project Code:

You can open the code we provided. The code used in this project is saved in (i.e., the path): ..\program-code\arduino-c-windows-code. (The path for the project code below is the same, i.e.: same as below.)

//**********************************************************************
/*
 * File name : LED Blinking
 * Description: Make the LED blink.
 */
#define PIN_LED   15  // Define the LED pin

// The setup function runs only once when reset or powered on
void setup() {
  // Initialize the digital pin LED as an output.
  pinMode(PIN_LED, OUTPUT);
}

// The loop function repeats forever
void loop() {
  digitalWrite(PIN_LED, HIGH);   // Turn on the LED (HIGH is high level)
  delay(500);                       // Delay 0.5s
  digitalWrite(PIN_LED, LOW);    // Turn off the LED, making the voltage low
  delay(500);                       // Delay 0.5s
}
//*************************************************************************************
Before uploading the project code to the ESP32, check the Arduino IDE configuration. (The steps for uploading project code below are the same, i.e.: same as below.)

Click "Tools" and confirm the "Board" type and "Port (COM)", as shown below: (Note: You can only see the corresponding port after connecting the ESP32 board to the computer via a USB cable.)

图片不存在

Click 图片不存在 to upload the project code to the ESP32 board.

图片不存在

Note: If the code upload is unsuccessful, click 图片不存在 again and press and hold the Boot button 图片不存在 on the ESP32 board with your hand. Release the Boot button after the upload progress percentage appears, as shown below:

图片不存在

Project code uploaded successfully!

图片不存在

5. Project Phenomenon:

After the project code is uploaded successfully, power it via the USB cable. You will see the LED in the circuit blink repeatedly.

图片不存在

Project 04 Breathing Light

1. Project Introduction:

In previous lessons, we know that an LED has on/off states. So how do we achieve an intermediate state? How do we output an intermediate state to make the LED "half-bright"? This is what we will learn. A breathing light is when the LED goes from off to on, and from on to off, just like "breathing." So how do we control the brightness of the LED? We will use the PWM of the ESP32 to achieve this goal.

2. Project Components:

图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Red LED*1
图片不存在 图片不存在 图片不存在
220Ω Resistor*1 Jumper Wires*2 USB Cable*1

3. Component Knowledge:

图片不存在

Analog Signal & Digital Signal

An analog signal is a signal that is continuous in both time and value. In contrast, a digital signal or discrete-time signal is a time series composed of a sequence of numbers. Most signals in life are analog signals. A familiar example of an analog signal is: the temperature throughout the day changes continuously, rather than abruptly jumping from 0 to 10 instantly. However, the values of a digital signal can change instantaneously, represented by the numbers 1 and 0 (the basis of binary code). As shown in the diagram below, we can more easily see the difference between them.

图片不存在

In practical applications, we often use binary as digital signals, i.e., a series of 0s and 1s. Since binary signals have only two values (0 or 1), they have great stability and reliability. Finally, analog and digital signals can be converted to each other.

PWM:

Pulse Width Modulation (PWM) is an effective method for controlling analog circuits using digital signals. Ordinary processors cannot directly output analog signals. PWM technology makes this conversion (converting digital signals to analog signals) very convenient. PWM technology uses digital pins to send square waves of a certain frequency, i.e., alternating high-level and low-level outputs. The total time of each set of high and low levels is generally fixed and is called the period (Note: the reciprocal of the period is the frequency). The duration of the high-level output is usually called the pulse width. The duty cycle is the percentage of the ratio of the pulse width (PW) to the total period (T) of the waveform. The longer the high-level output duration, the longer the duty cycle, and the higher the corresponding voltage in the analog signal. The diagram below shows the corresponding analog signal voltage varying between 0V and 3.3V (high level is 3.3V) for pulse widths from 0% to 100%.

图片不存在

The longer the PWM duty cycle, the higher the output power. Now that we understand this relationship, we can use PWM to control the brightness of an LED or the speed of a DC motor, etc. As can be seen from the above, PWM is not a real analog signal; the effective voltage value equals the corresponding analog signal. Therefore, we can control the output power of LEDs and other output modules to achieve different effects.

ESP32 and PWM

On the ESP32, the LEDC (PWM) controller has 16 independent channels. Each channel can independently control frequency, duty cycle, and even resolution. Unlike traditional PWM pins, the PWM output pins of the ESP32 are configurable, and each channel has one or more PWM output pins. The relationship between maximum frequency and bit resolution is shown in the formula below:

图片不存在

Where the maximum value of bits is 31. For example: generating PWM with 8-bit precision (2^8 = 256. The value range is 0 to 255), the maximum frequency is 80,000,000/255 = 312,500Hz.)

4. Project Wiring Diagram:

图片不存在

5. Project Code:

This project is designed to output PWM from GPIO15, with the pulse width gradually increasing from 0% to 100%, then gradually decreasing from 100% to 0%.

You can open the code we provided. The code used in this project is saved in (i.e., the path): ..\program-code\arduino-c-windows-code. (The path for the project code below is the same, i.e.: same as below.)

//**********************************************************************
/*
 * File name : Breathing Light
 * Description: Make the LED flash on and off like breathing.
 */
#define PIN_LED   15  // Define the LED pin
#define CHN       0  // Define the PWM channel
#define FRQ       1000  // Define the PWM frequency
#define PWM_BIT   8    // Define the PWM resolution
void setup() {
  // If you have ESP32 board version 2.X installed, use this code
  ledcSetup(CHN, FRQ, PWM_BIT); // Set the PWM channel
  ledcAttachPin(PIN_LED, CHN);  // Attach the LED pin to the PWM channel

  // If you have ESP32 board version 3.X or newer installed, use this code
  // ledcAttach(CHN, FRQ, PWM_BIT); // Set the PWM channel
  // ledcWrite(PIN_LED, CHN);  // Attach the LED pin to the PWM channel
}

void loop() {
  for (int i = 0; i < 255; i++) { // Make the LED gradually brighter
    ledcWrite(CHN, i);
    delay(10);
  }
  for (int i = 255; i > -1; i--) {  // Make the LED gradually dimmer
    ledcWrite(CHN, i);
    delay(10);
  }
}
//*************************************************************************************
Before uploading the project code to the ESP32, check the Arduino IDE configuration. (The steps for uploading project code below are the same, i.e.: same as below.)

Click "Tools" and confirm the "Board" type and "Port (COM)", as shown below: (Note: You can only see the corresponding port after connecting the ESP32 board to the computer via a USB cable.)

图片不存在

Click 图片不存在 to upload the project code to the ESP32 board.

图片不存在

Note: If the code upload is unsuccessful, click 图片不存在 again and press and hold the Boot button 图片不存在 on the ESP32 board with your hand. Release the Boot button after the upload progress percentage appears, as shown below:

图片不存在

Project code uploaded successfully!

图片不存在

6. Project Phenomenon:

After the project code is uploaded successfully, power it via the USB cable. You will see the LED in the circuit gradually brighten from dim, then gradually dim from bright, just like breathing.

图片不存在

Project 05 Traffic Light

1. Project Introduction:

Traffic lights are very common in our daily lives. Following a certain time pattern, traffic lights consist of three colors: red, yellow, and green. Everyone should follow traffic rules, which can prevent many traffic accidents. In this project, we will use the ESP32 and some LEDs (red, yellow, green) to simulate a traffic light.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Red LED*1 Yellow LED*1
图片不存在 图片不存在 图片不存在 图片不存在
Green LED*1 220Ω Resistor*3 Jumper Wires (several) USB Cable*1

3. Project Wiring Diagram:

图片不存在

4. Project Code:

You can open the code we provided. The code used in this project is saved in (i.e., the path): ..\program-code\arduino-c-windows-code. (The path for the project code below is the same, i.e.: same as below.)

//**********************************************************************
/*
 * File name  : Traffic Light
 * Description: Simulate a traffic light.
 */
#define PIN_LED_RED   0  // Define the red pin
#define PIN_LED_YELLOW   2  // Define the yellow pin
#define PIN_LED_GREEN  15  // Define the green pin

void setup() {
  pinMode(PIN_LED_RED, OUTPUT);
  pinMode(PIN_LED_YELLOW, OUTPUT);
  pinMode(PIN_LED_GREEN, OUTPUT);
}

void loop() {
   digitalWrite(PIN_LED_RED, HIGH);// Turn on the red light
   delay(5000);// Delay 5s
   digitalWrite(PIN_LED_RED, LOW); // Turn off the red light
   delay(500);// Delay 0.5s
   for(int i=0;i<3;i++)// Blink 3 times.
  {
   digitalWrite(PIN_LED_YELLOW, HIGH);// Turn on the yellow light
   delay(500);// Delay 0.5s
   digitalWrite(PIN_LED_YELLOW, LOW);// Turn off the yellow light
   delay(500);// Delay 0.5s
   } 
   digitalWrite(PIN_LED_GREEN, HIGH);// Turn on the green light
   delay(5000);// Delay 5s
   digitalWrite(PIN_LED_GREEN, LOW);// 
  delay(500);// Delay 0.5s
}
//*************************************************************************************
Before uploading the project code to the ESP32, check the Arduino IDE configuration. (The steps for uploading project code below are the same, i.e.: same as below.)

Click "Tools" and confirm the "Board" type and "Port (COM)", as shown below: (Note: You can only see the corresponding port after connecting the ESP32 board to the computer via a USB cable.)

图片不存在

Click 图片不存在 to upload the project code to the ESP32 board.

图片不存在

Note: If the code upload is unsuccessful, click 图片不存在 again and press and hold the Boot button 图片不存在 on the ESP32 board with your hand. Release the Boot button after the upload progress percentage appears, as shown below:

图片不存在

Project code uploaded successfully!

图片不存在

5. Project Phenomenon:

After the project code is uploaded successfully, power it via the USB cable. You will see: 1. First, the red light will be on for 5 seconds, then off; 2. Next, the yellow light will blink 3 times, then off; 3. Then, the green light will be on for 5 seconds, then off; 4. Continue repeating steps 1-3.

图片不存在

Project 06 RGB LED

图片不存在

1. Project Introduction:

An RGB LED consists of three colors (red, green, blue). By mixing these three primary colors, it can emit different colors. In this project, we will introduce the RGB LED and show you how to use the ESP32 to control the RGB LED to emit different colors. Even though the RGB LED is very basic, it is a great way to introduce yourself or others to the fundamentals of electronics and coding.

2. Project Components:

图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 RGB LED*1
图片不存在 图片不存在 图片不存在
220Ω Resistor*3 Jumper Wires (several) USB Cable*1

3. Component Knowledge:

Most displays follow the RGB color standard. All colors on a computer screen are produced by mixing red, green, and blue in different proportions.

图片不存在

This RGB LED has 4 pins: one for each color (red, green, blue) and a common cathode. To change the brightness of the RGB LED, we can use the PWM pins of the ESP. The PWM pins will provide signals with different duty cycles to the RGB LED to achieve different colors.

If we use three 10-bit PWMs to control the RGB LED, theoretically we can create 2^10 × 2^10 × 2^10 = 1,073,741,824 (1 billion) colors through different combinations.

4. Project Wiring Diagram:

图片不存在

5. Project Code:

//**********************************************************************
/*
 * File name  : RGB LED
 * Description: Use RGB to display random colors.
 */
int ledPins[] = {0, 2, 15};    // Define red, green, blue pins
const byte chns[] = {0, 1, 2};        // Define PWM channels
int red, green, blue;
void setup() {
  for (int i = 0; i < 3; i++) {   // Set up PWM channels, 1KHz, 8-bit
    ledcSetup(chns[i], 1000, 8);
    ledcAttachPin(ledPins[i], chns[i]);
  }
}

void loop() {
  red = random(0, 256);
  green = random(0, 256);
  blue = random(0, 256);
  setColor(red, green, blue);
  delay(200);
}

void setColor(byte r, byte g, byte b) {
  ledcWrite(chns[0], 255 - r); // Common cathode LED, high level turns on the LED.
  ledcWrite(chns[1], 255 - g);
  ledcWrite(chns[2], 255 - b);
}
//*************************************************************************************

6. Project Phenomenon:

After the code is uploaded successfully and powered via the USB cable, you will see the RGB LED start displaying random colors.

图片不存在

Project 07 Flowing Light

1. Project Introduction:

In daily life, we can see many billboards composed of LEDs of different colors. They continuously change the lights (like flowing water) to attract customers' attention. In this project, we will use the ESP32 to control 10 LEDs to achieve a flowing light effect.

2. Project Components:

图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Red LED*10
图片不存在 图片不存在 图片不存在
220Ω Resistor*10 Jumper Wires (several) USB Cable*1

3. Project Wiring Diagram:

图片不存在

4. Project Code:

This project designs and creates a flowing light. Here are the actions: first turn on LED #1, then turn it off. Then turn on LED #2, then turn it off... and repeat the same for all 10 LEDs until the last LED is turned off. This process repeats to achieve the "motion" of flowing water.

//**********************************************************************
/* 
 * File name : Flowing Light
 * Description: Use ten LEDs to demonstrate a flowing light
 */
byte ledPins[] = {22, 21, 19, 18, 17, 16, 4, 0, 2, 15};
int ledCounts;

void setup() {
  ledCounts = sizeof(ledPins);
  for (int i = 0; i < ledCounts; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop() {
  for (int i = 0; i < ledCounts; i++) {
    digitalWrite(ledPins[i], HIGH);
    delay(100);
    digitalWrite(ledPins[i], LOW);
  }
  for (int i = ledCounts - 1; i > -1; i--) {
    digitalWrite(ledPins[i], HIGH);
    delay(100);
    digitalWrite(ledPins[i], LOW);
  }
}
//**********************************************************************

5. Project Phenomenon:

After the code is uploaded successfully and powered via the USB cable, you will see: 10 LEDs will light up from left to right, then return from right to left.

图片不存在

Project 08 One-Digit Digital Tube

1. Project Introduction:

A seven-segment display is an electronic display device for showing decimal numbers. It is widely used in digital clocks, electronic instruments, basic calculators, and other electronic devices that display numeric information. Even bombs seen in movies have seven-segment displays. Perhaps seven-segment displays do not look modern, but they are an alternative to more complex dot-matrix displays and are easy to use in limited lighting conditions and strong sunlight. In this project, we will use the ESP32 to control a one-digit digital tube to display numbers.

2. Project Components:

图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 One-digit Digital Tube*1
图片不存在 图片不存在 图片不存在
220Ω Resistor*8 Jumper Wires (several) USB Cable*1

3. Component Knowledge:

图片不存在

One-Digit Digital Tube Display Principle: A digital display is a semiconductor light-emitting device. Its basic unit is a light-emitting diode (LED). Digital displays can be divided into 7-segment and 8-segment displays by the number of segments. An 8-segment display has one more LED unit than a 7-segment display (used for decimal point display). Each segment of a seven-segment LED display is a separate LED. According to the wiring method of the LED units, digital tubes can be divided into common anode and common cathode digital tubes.

In a common cathode 7-segment digital tube, the cathodes (or negative terminals) of all segment LEDs are connected together. You should connect the common cathode to GND. To light up a segment LED, you can set its associated pin to HIGH.

In a common anode 7-segment digital tube, the anodes (positive terminals) of all segment LEDs are connected together. You should connect the common anode to +5V. To light up a segment LED, you can set its associated pin to LOW.

图片不存在

Each segment of the digital tube consists of an LED. So when you use it, you also need to use a current-limiting resistor. Otherwise, the LED will be burned out. In this experiment, we use a common cathode one-digit digital tube. As mentioned above, you should connect the common cathode to GND. To light up a segment LED, you can set its associated pin to HIGH.

4. Project Wiring Diagram:

Note: Insert the seven-segment digital tube into the breadboard in the same direction as shown in the wiring diagram, with an extra dot in the bottom-right corner.

图片不存在

图片不存在

5. Project Code:

A digital display consists of 7 segments, and the decimal point display consists of 1 segment. When displaying certain numbers, the corresponding segments will be lit. For example, when displaying the number 1, segments b and c will be turned on.

//**********************************************************************
/* 
 * File name : One-Digit Digital Tube
 * Description: The one-digit tube displays numbers from 9 to 0.
 */
// Set the IO PIN for each segment
int a=16; // Segment a digital PIN 16
int b=4; // Segment b digital PIN 4
int c=5; // Segment c digital PIN 5
int d=18; // Segment d digital PIN 18
int e=19; // Segment e digital PIN 19
int f=22; // Segment f digital PIN 22
int g=23; // Segment g digital PIN 23
int dp=17; // Segment dp digital PIN 17
void digital_0(void) // Display the number 0
{
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(e,HIGH);
digitalWrite(f,HIGH);
digitalWrite(g,LOW);
digitalWrite(dp,LOW);
}
void digital_1(void) // Display the number 1
{
digitalWrite(a,LOW);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(f,LOW);
digitalWrite(g,LOW);
digitalWrite(dp,LOW);
}
void digital_2(void) // Display the number 2
{
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,LOW);
digitalWrite(d,HIGH);
digitalWrite(e,HIGH);
digitalWrite(f,LOW);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void digital_3(void) // Display the number 3
{
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(f,LOW);
digitalWrite(e,LOW);
digitalWrite(dp,LOW);
digitalWrite(g,HIGH);
}
void digital_4(void) // Display the number 4
{
digitalWrite(a,LOW);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void digital_5(void) // Display the number 5
{
digitalWrite(a,HIGH);
digitalWrite(b,LOW);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(e,LOW);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void digital_6(void) // Display the number 6
{
digitalWrite(a,HIGH);
digitalWrite(b,LOW);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(e,HIGH);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void digital_7(void) // Display the number 7
{
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(f,LOW);
digitalWrite(g,LOW);
digitalWrite(dp,LOW);
}
void digital_8(void) // Display the number 8
{
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(e,HIGH);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void digital_9(void) // Display the number 9
{
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(e,LOW);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void setup()
{
  // Initialize the digital pins LED as outputs.
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(e, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(g, OUTPUT);
  pinMode(dp, OUTPUT);
}
void loop()
{
while(1)
{
digital_9();// Display the number 9
delay(1000); // Delay 1s
digital_8();// Display the number 8
delay(1000); 
digital_7();// Display the number 7
delay(1000); 
digital_6();// Display the number 6
delay(1000); 
digital_5();// Display the number 5
delay(1000); 
digital_4();// Display the number 4
delay(1000); 
digital_3();// Display the number 3
delay(1000); 
digital_2();// Display the number 2
delay(1000);
digital_1();// Display the number 1
delay(1000);
digital_0();// Display the number 0
delay(1000);
}}
//**********************************************************************

6. Project Phenomenon:

After the code is uploaded successfully and powered via the USB cable, you will see: the one-digit digital tube will display numbers from 9 to 0.

图片不存在

Project 09 Four-Digit Digital Tube

1. Project Introduction:

A four-digit digital tube is a very practical display device. It is needed for electronic clocks, scoreboards on sports fields, and people counters in parks. Due to its low price and ease of use, more and more projects will use 4-digit digital tubes. In this project, we use the ESP32 to control a four-digit digital tube to display numbers.

2. Project Components:

图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Four-digit Digital Tube*1
图片不存在 图片不存在 图片不存在
220Ω Resistor*8 Jumper Wires (several) USB Cable*1

3. Component Knowledge:

图片不存在

Four-Digit Digital Tube: There are common anode and common cathode four-digit digital tubes. The display principle is similar to that of a one-digit digital tube. Both use 8 GPIO ports to control the display segments, which are 8 LEDs. However, since this is a 4-digit display, 4 more GPIO ports are needed to control the digit selection pins, i.e., choosing which individual digital tube is lit. The digits switch so quickly that the human eye cannot distinguish it, so it appears that multiple digital tubes are displaying simultaneously.

Our four-digit digital tube is common cathode.

The diagram below shows the pinout of the 4-digit digital tube. G1, G2, G3, and G4 are the pins that control the digits.

图片不存在

The diagram below shows the internal wiring schematic of the 4-digit digital tube.

图片不存在

图片不存在

4. Project Wiring Diagram:

图片不存在

5. Project Code:

//**********************************************************************
/* 
 * File name  : Four-Digit Digital Tube
 * Description: The four-digit tube displays numbers from 0 to 9999.
 */
#define d_a 18  // Define digital tube segment a to pin 18
#define d_b 13
#define d_c 2
#define d_d 16
#define d_e 17
#define d_f 19
#define d_g 0
#define d_dp 4

#define G1 21  // Define the first group nixie tube G1 to pin 21
#define G2 22
#define G3 14
#define G4 15

// Digital tube 0-F code values
unsigned char num[17][8] =
{
 //a  b  c  d  e  f  g  dp 
  {1, 1, 1, 1, 1, 1, 0, 0},     //0
  {0, 1, 1, 0, 0, 0, 0, 0},     //1
  {1, 1, 0, 1, 1, 0, 1, 0},     //2
  {1, 1, 1, 1, 0, 0, 1, 0},     //3
  {0, 1, 1, 0, 0, 1, 1, 0},     //4
  {1, 0, 1, 1, 0, 1, 1, 0},     //5
  {1, 0, 1, 1, 1, 1, 1, 0},     //6
  {1, 1, 1, 0, 0, 0, 0, 0},     //7
  {1, 1, 1, 1, 1, 1, 1, 0},     //8
  {1, 1, 1, 1, 0, 1, 1, 0},     //9
  {1, 1, 1, 0, 1, 1, 1, 1},     //A
  {1, 1, 1, 1, 1, 1, 1, 1},     //B
  {1, 0, 0, 1, 1, 1, 0, 1},     //C
  {1, 1, 1, 1, 1, 1, 0, 1},     //D
  {1, 0, 0, 1, 1, 1, 1, 1},     //E
  {1, 0, 0, 0, 1, 1, 1, 1},     //F
  {0, 0, 0, 0, 0, 0, 0, 1},     //.
};

void setup()
{
  pinMode(d_a,OUTPUT);    // Set as output pins
  pinMode(d_b,OUTPUT);
  pinMode(d_c,OUTPUT);
  pinMode(d_d,OUTPUT);
  pinMode(d_e,OUTPUT);
  pinMode(d_f,OUTPUT);
  pinMode(d_g,OUTPUT);
  pinMode(d_dp,OUTPUT);

  pinMode(G1,OUTPUT);
  pinMode(G2,OUTPUT);
  pinMode(G3,OUTPUT);
  pinMode(G4,OUTPUT);
}

void loop()
{

  // Start counting from 0, incrementing by 1 up to 9999, repeating.
  for(int l = 0;l < 10;l++ )
  {
    for(int k = 0; k < 10;k++)
    {
      for(int j = 0; j < 10; j++)
      {
        for(int i = 0;i < 10;i++)
        {
          // Blinking 125 times per second equals 1 second.
          // 1000/8=125
          for(int q = 0;q<125;q++)
          {
            Display(1,l);// The first digital tube displays the value of l.
            delay(2);
            Display(2,k);
            delay(2);
            Display(3,j);
            delay(2);
            Display(4,i);
            delay(2);
          }

        }
      }
    }
  }


}

// Display function: g ranges from 1 to 4, num ranges from 0 to 9
void Display(unsigned char g,unsigned char n) 
{
  digitalWrite(d_a,LOW);      // Turn off the corresponding LED segment
  digitalWrite(d_b,LOW);
  digitalWrite(d_c,LOW);
  digitalWrite(d_d,LOW);
  digitalWrite(d_e,LOW);
  digitalWrite(d_f,LOW);
  digitalWrite(d_g,LOW);
  digitalWrite(d_dp,LOW);

  switch(g)           // Select
  {
    case 1:
      digitalWrite(G1,LOW);   // Select the first digit
      digitalWrite(G2,HIGH);
      digitalWrite(G3,HIGH);
      digitalWrite(G4,HIGH);
      break;
    case 2:
      digitalWrite(G1,HIGH);
      digitalWrite(G2,LOW);   // Select the second digit
      digitalWrite(G3,HIGH);
      digitalWrite(G4,HIGH);
      break;
    case 3:
      digitalWrite(G1,HIGH);
      digitalWrite(G2,HIGH);
      digitalWrite(G3,LOW);   // Select the third digit
      digitalWrite(G4,HIGH);
      break;
    case 4:
      digitalWrite(G1,HIGH);
      digitalWrite(G2,HIGH);
      digitalWrite(G3,HIGH);
      digitalWrite(G4,LOW);   // Select the fourth digit
      break;
    default:break;
  }

  digitalWrite(d_a,num[n][0]);      // Look up the code value table for segment a
  digitalWrite(d_b,num[n][1]);
  digitalWrite(d_c,num[n][2]);
  digitalWrite(d_d,num[n][3]);
  digitalWrite(d_e,num[n][4]);
  digitalWrite(d_f,num[n][5]);
  digitalWrite(d_g,num[n][6]);
  digitalWrite(d_dp,num[n][7]);
}
//**********************************************************************

6. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: the four-digit digital tube starts counting from 0000, incrementing by 1 up to 9999, and repeats these actions in an infinite loop.

图片不存在

Project 10 8×8 Dot Matrix Display

1. Project Introduction:

A dot matrix display is an electronic digital display device that can display information on machines, clocks, public transport departure indicators, and many other devices. In this project, we will use the ESP32 to control an 8x8 LED dot matrix to display patterns.

2. Project Components:

图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 8×8 Dot Matrix Display*1
图片不存在 图片不存在 图片不存在
220Ω Resistor*8 Jumper Wires (several) USB Cable*1

3. Component Knowledge:

8×8 Dot Matrix: It consists of 64 LEDs and comes in two types: common anode by row and common cathode by row. Our module is common anode by row, meaning each row has one wire connecting the anodes of the LEDs together, and the columns connect the cathodes of the LEDs together. See the figure below:

图片不存在

Each LED is placed at the intersection of a row and a column. When a row is at level 1 and a column is at level 0, the corresponding LED lights up. If you want to light up the LED at the first position, you should set pin 9 to high and pin 13 to low. If you want to light up the LEDs in the first row, you should set pin 9 to high and pins 13, 3, 4, 10, 6, 11, 15, and 16 to low. If you want to light up the LEDs in the first column, set pin 13 to low and pins 9, 14, 8, 12, 1, 7, 2, and 5 to high.

The external view of the 8×8 dot matrix display is shown below:

图片不存在

图片不存在

图片不存在

4. Project Wiring Diagram:

图片不存在

5. Project Code:

//**********************************************************************************
/* 
 * File name  : 8×8 Dot Matrix Display
 * Description: 8×8 dot matrix displays numbers from 0 to 9.
 */
int R[] = {14,26,4,27,19,16,18,17};
int C[] = {32,21,22,12,0,13,33,25};

unsigned char data_0[8][8] =
{
{0,0,1,1,1,0,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,0,1,1,1,0,0,0}
};

unsigned char data_1[8][8] =
{
{0,0,0,0,1,0,0,0},
{0,0,0,1,1,0,0,0},
{0,0,0,0,1,0,0,0},
{0,0,0,0,1,0,0,0},
{0,0,0,0,1,0,0,0},
{0,0,0,0,1,0,0,0},
{0,0,0,0,1,0,0,0},
{0,0,0,1,1,1,0,0}
};

unsigned char data_2[8][8] =
{
{0,0,1,1,1,0,0,0},
{0,1,0,0,0,1,0,0},
{0,0,0,0,0,1,0,0},
{0,0,0,0,1,0,0,0},
{0,0,0,1,0,0,0,0},
{0,0,1,0,0,0,0,0},
{0,1,1,1,1,1,0,0},
{0,0,0,0,0,0,0,0}
};

unsigned char data_3[8][8] =
{
{0,0,1,1,1,1,0,0},
{0,0,0,0,0,1,0,0},
{0,0,0,0,0,1,0,0},
{0,0,1,1,1,1,0,0},
{0,0,0,0,0,1,0,0},
{0,0,0,0,0,1,0,0},
{0,0,1,1,1,1,0,0},
{0,0,0,0,0,0,0,0}
};

unsigned char data_4[8][8] =
{
{0,1,0,0,0,0,0,0},
{0,1,0,0,1,0,0,0},
{0,1,0,0,1,0,0,0},
{0,1,1,1,1,1,1,0},
{0,0,0,0,1,0,0,0},
{0,0,0,0,1,0,0,0},
{0,0,0,0,1,0,0,0},
{0,0,0,0,0,0,0,0}
};

unsigned char data_5[8][8] =
{
{0,1,0,0,0,0,0,0},
{0,1,1,1,1,1,0,0},
{0,1,0,0,0,0,0,0},
{0,1,1,1,1,1,0,0},
{0,0,0,0,0,1,0,0},
{0,0,0,0,0,1,0,0},
{0,1,1,1,1,1,0,0},
{0,0,0,0,0,0,0,0}
};

unsigned char data_6[8][8] =
{
{0,1,1,1,1,1,0,0},
{0,1,0,0,0,0,0,0},
{0,1,0,0,0,0,0,0},
{0,1,1,1,1,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,1,1,1,1,0,0},
{0,0,0,0,0,0,0,0}
};

unsigned char data_7[8][8] =
{
{0,0,0,0,0,0,0,0},
{0,1,1,1,1,1,0,0},
{0,0,0,0,0,1,0,0},
{0,0,0,0,1,0,0,0},
{0,0,0,1,0,0,0,0},
{0,0,1,0,0,0,0,0},
{0,1,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0}
};

unsigned char data_8[8][8] =
{
{0,1,1,1,1,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,1,1,1,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,1,1,1,1,0,0},
{0,0,0,0,0,0,0,0}
};

unsigned char data_9[8][8] =
{
{0,1,1,1,1,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,1,1,1,1,0,0},
{0,0,0,0,0,1,0,0},
{0,0,0,0,0,1,0,0},
{0,1,1,1,1,1,0,0},
{0,0,0,0,0,0,0,0}
};

void Display(unsigned char dat[8][8])
{
for(int c = 0; c<8;c++)
{
digitalWrite(C[c],LOW);
for(int r = 0;r<8;r++)
{
digitalWrite(R[r],dat[r][c]);
}
delay(1);
Clear();
}
}

void Clear()
{
for(int i = 0;i<8;i++)
{
digitalWrite(R[i],LOW);
digitalWrite(C[i],HIGH);
}
}

void setup(){
  for(int i = 0;i<8;i++)
  {
    pinMode(R[i],OUTPUT);
    pinMode(C[i],OUTPUT);
  }

}

void loop(){
  for (int i = 1; i <= 100; i = i + (1)) {
    Display(data_0);
  }
  for (int i = 1; i <= 100; i = i + (1)) {
    Display(data_1);
  }
  for (int i = 1; i <= 100; i = i + (1)) {
    Display(data_2);
  }
  for (int i = 1; i <= 100; i = i + (1)) {
    Display(data_3);
  }
  for (int i = 1; i <= 100; i = i + (1)) {
    Display(data_4);
  }
  for (int i = 1; i <= 100; i = i + (1)) {
    Display(data_5);
  }
  for (int i = 1; i <= 100; i = i + (1)) {
    Display(data_6);
  }
  for (int i = 1; i <= 100; i = i + (1)) {
    Display(data_7);
  }
  for (int i = 1; i <= 100; i = i + (1)) {
    Display(data_8);
  }
  for (int i = 1; i <= 100; i = i + (1)) {
    Display(data_9);
  }
}
//**********************************************************************************

6. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: the 8*8 dot matrix display shows numbers 0~9 sequentially in a loop.

图片不存在

Project 11 Shift Register Controlling 8 LEDs

1. Project Introduction:

In the previous project, we have learned how to light up an LED.

Usually, a development board has a limited number of I/O ports. If you need to control a large number of devices, you may run out of I/O ports. For example, in Project 2, each LED requires one I/O port. If you need to control multiple LEDs, you will run out of I/O ports. To handle this scenario, we introduce a shift register to expand the I/O ports. In this project, we will use the ESP32, the 74HC595 chip, and LEDs to create a flowing light to understand the function of the 74HC595 chip.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 74HC595N Chip*1 Red LED*8
图片不存在 图片不存在 图片不存在
220Ω Resistor*8 Jumper Wires (several) USB Cable*1

3. Component Knowledge:

图片不存在

74HC595N Chip: This chip has an 8-bit shift register and a memory, as well as tri-state output capability. Simply put, its main function is to "use a small number of I/O ports to expand multiple output ports." Normally, controlling 8 LEDs requires 8 GPIO pins on the ESP32. But with the 74HC595N, you only need 3 GPIO pins to easily control 8 outputs, and it can be expanded infinitely through cascading.

If you want to learn more, you can check the relevant resources Click to jump

Img

Pin Description:

Pin: Pin Description:
Pin 13 OE It is an output enable pin, used to ensure whether the latch data is input to the Q0-Q7 pins. At low level, high level is not output. In this experiment, we directly connect it to GND to maintain a low level for data output.
Pin 14 SI/DS This is the pin where the 74HC595 receives data, i.e., the serial data input. Only one bit can be input at a time, so entering 8 consecutive times makes a byte.
Pin 10 SCLR/MR A pin that initializes the storage register. At low level, it initializes the internal storage register. In this experiment, we connect it to VCC to maintain a high level.
Pin 11 SCK/SH_CP The clock pin of the shift register. On the rising edge, the data in the shift register shifts backward as a whole and receives new data input.
Pin 12 RCK/ST_CP The clock input pin of the storage register. On the rising edge, data is transferred from the shift register to the storage register. At this point, the data is output in parallel from the Q0~Q7 ports.
Pin 9 SQH This pin is a serial output pin, specifically used for chip cascading, connecting to the SI pin of the next 74HC595.
Q0--Q7 (Pin 15, Pins 1-7) 8-bit parallel output, can directly control the 8 segments of a digital tube.

4. Project Wiring Diagram:

Note: Pay attention to the orientation of the 74HC595N chip when inserting it.

图片不存在

图片不存在

5. Project Code:

//**********************************************************************
/* 
 * File name : 74HC595N Controlling 8 LEDs
 * Description: Use 74HC595N to drive ten LEDs in a flowing light.
 */
int dataPin = 14;   // Pin connected to 74HC595 DS (Pin14)  
int latchPin = 12;  // 74HC595 ST_CP connection pin (Pin12)
int clockPin = 13;  // 74HC595 SH_CP connection pin (Pin11)          

void setup() {
  // Set pin outputs
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
  // Define a single-byte variable using 8 bits to represent the state of the 8 LEDs in the LED bar graph.
  // This variable is assigned 0x01, i.e., binary 00000001, meaning only one LED is on.
  byte x = 0x01;    // 0b 0000 0001
  for (int j = 0; j < 8; j++) { // Let the LEDs light up from right to left
    writeTo595(LSBFIRST, x);
    x <<= 1; // Shift the variable left by one bit, and the lit LED moves one step to the left.
    delay(50);
  }
  delay(100);
  x = 0x80;       //0b 1000 0000
  for (int j = 0; j < 8; j++) { // Let the LEDs light up from left to right
    writeTo595(LSBFIRST, x);
    x >>= 1;    
    delay(50);
  }
  delay(100);
}
void writeTo595(int order, byte _data ) {
  // Output low level to latchPin
  digitalWrite(latchPin, LOW);
  // Send serial data to 74HC595
  shiftOut(dataPin, clockPin, order, _data);
  // Output high level to latchPin, 74HC595 updates the data to the parallel output ports.
  digitalWrite(latchPin, HIGH);
}
//**********************************************************************************

6. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: 8 LEDs start flashing in a flowing light pattern.

图片不存在

Project 12 Active Buzzer

1. Project Introduction:

An active buzzer is a sound-producing component. It is widely used as a sound element in computers, printers, alarm devices, electronic toys, telephones, timers, etc. It has an internal vibration source. Just connect it to a 5V power supply and it will continuously emit a buzzing sound. In this project, we will use the ESP32 to control the active buzzer to emit a "beep beep" sound.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Active Buzzer*1 NPN Transistor (S8050)*1
图片不存在 图片不存在 图片不存在
1KΩ Resistor*1 Jumper Wires (several) USB Cable*1

3. Component Knowledge:

图片不存在

Active Buzzer: It has a simple oscillator circuit inside that converts constant DC power into a pulse signal of a specific frequency. Once the active buzzer receives a high level, it will produce sound. A passive buzzer, on the other hand, is an integrated electronic buzzer without an internal vibration source. It must be driven by a 2K-5K square wave, not a DC signal. The appearance of these two buzzers is very similar, but a buzzer with a green circuit board is a passive buzzer, while one with black tape is an active buzzer. Passive buzzers cannot distinguish polarity, while active buzzers can, as shown below:

图片不存在

图片不存在

Transistor: Since the buzzer requires a large current and the GPIO output capability of the ESP32 cannot meet the requirement, an NPN transistor is needed here to amplify the current. A transistor, full name: semiconductor transistor, is a semiconductor device that controls current. A transistor can be used to amplify weak signals or as a switch. It has three electrodes (pins): base (b), collector (c), and emitter (e). When current passes between "be," "ce" will allow several times the current to pass through (transistor amplification); at this point, the transistor is operating in the amplification region. When the current between "be" exceeds a certain value, "ce" will no longer allow the current to increase; at this point, the transistor is operating in the saturation region. There are two types of transistors as shown below: PNP and NPN.

图片不存在

In our kit, the PNP transistor is marked as 8550, and the NPN transistor is marked as 8050.

Based on the characteristics of transistors, they are often used as switches in digital circuits. Since the current output capability of a microcontroller is very weak, we will use transistors to amplify current and drive high-current components. When using an NPN transistor to drive a buzzer, the following method is usually adopted: if the GPIO outputs a high level, current will flow through R1, the transistor will conduct, and the buzzer will sound. If the GPIO outputs a low level, no current flows through R1, the transistor will not conduct, and the buzzer will not sound. When using a PNP transistor to drive a buzzer, the following method is usually adopted: if the GPIO outputs a low level, current will flow through R1, the transistor will conduct, and the buzzer will sound. If the GPIO outputs a high level, no current flows through R1, the transistor will not conduct, and the buzzer will not sound.

图片不存在

4. Project Wiring Diagram:

图片不存在

Note: The buzzer in this circuit is powered by 5V. At 3.3V, the buzzer can work but with reduced loudness.

5. Project Code:

//**********************************************************************
/* 
 * File name   : Active Buzzer
 * Description: Active buzzer sounds.
 */
#define buzzerPin  15  // Define the buzzer pin

void setup ()
{
  pinMode (buzzerPin, OUTPUT);
}
void loop ()
{
  digitalWrite (buzzerPin, HIGH);
  delay (500);
  digitalWrite (buzzerPin, LOW);
  delay (500);
}
//**********************************************************************************

6. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: the active buzzer emits a "beep beep" sound.

图片不存在

Project 13 Passive Buzzer

1. Project Introduction:

In the previous project, we studied the active buzzer, which can only emit one sound and may feel monotonous. This project will cover another type of buzzer, the passive buzzer. Unlike the active buzzer, the passive buzzer can emit sounds of different frequencies. In this project, you will use the ESP32 to control the passive buzzer.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Passive Buzzer*1 NPN Transistor (S8050)*1
图片不存在 图片不存在 图片不存在
1KΩ Resistor*1 Jumper Wires (several) USB Cable*1

3. Component Knowledge:

图片不存在

Passive Buzzer: It is an integrated electronic buzzer without an internal vibration source. It must be driven by a 2K-5K square wave, not a DC signal. The appearance of these two buzzers is very similar, but a buzzer with a green circuit board is a passive buzzer, while one with black tape is an active buzzer. Passive buzzers cannot distinguish polarity, while active buzzers can, as shown below:

图片不存在

Transistor: Please refer to Project 12.

4. Project Wiring Diagram:

图片不存在

5. Project Code:

//**********************************************************************
/*
 * File name   : Passive Buzzer
 * Description: Passive buzzer sounds an alarm.
 */
#define LEDC_CHANNEL_0 0

// LEDC timer uses 13-bit precision

#define LEDC_TIMER_13_BIT  13

// Define utility I/O ports

#define BUZZER_PIN  15

// Create a music melody list

int melody[] = {330, 330, 330, 262, 330, 392, 196, 262, 196, 165, 220, 247, 233, 220, 196, 330, 392, 440, 349, 392, 330, 262, 294, 247, 262, 196, 165, 220, 247, 233, 220, 196, 330, 392,440, 349, 392, 330, 262, 294, 247, 392, 370, 330, 311, 330, 208, 220, 262, 220, 262,

294, 392, 370, 330, 311, 330, 523, 523, 523, 392, 370, 330, 311, 330, 208, 220, 262,220, 262, 294, 311, 294, 262, 262, 262, 262, 262, 294, 330, 262, 220, 196, 262, 262,262, 262, 294, 330, 262, 262, 262, 262, 294, 330, 262, 220, 196};

// Create a note duration list

int noteDurations[] = {8,4,4,8,4,2,2,3,3,3,4,4,8,4,8,8,8,4,8,4,3,8,8,3,3,3,3,4,4,8,4,8,8,8,4,8,4,3,8,8,2,8,8,8,4,4,8,8,4,8,8,3,8,8,8,4,4,4,8,2,8,8,8,4,4,8,8,4,8,8,3,3,3,1,8,4,4,8,4,8,4,8,2,8,4,4,8,4,1,8,4,4,8,4,8,4,8,2};
void setup() {
pinMode(BUZZER_PIN, OUTPUT); // Set the buzzer as output mode
}

void loop() {

  int noteDuration; // Create a variable noteDuration

  for (int i = 0; i < sizeof(noteDurations); ++i)

  {
      noteDuration = 800/noteDurations[i];

      ledcSetup(LEDC_CHANNEL_0, melody[i]*2, LEDC_TIMER_13_BIT);

      ledcAttachPin(BUZZER_PIN, LEDC_CHANNEL_0);

      ledcWrite(LEDC_CHANNEL_0, 50);

      delay(noteDuration * 1.30); // Delay
  }
}
//**********************************************************************

6. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: the passive buzzer plays music.

图片不存在

Project 14 Small Desk Lamp

1. Project Introduction:

Did you know that the ESP32 can light up an LED when you press an external button? In this project, we will use the ESP32, a button switch, and an LED to make a mini desk lamp.

2. Project Components:

图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Button*1
图片不存在 图片不存在 图片不存在
10KΩ Resistor*1 Red LED*1 220Ω Resistor*1
图片不存在 图片不存在 图片不存在
Button Cap*1 Jumper Wires (several) USB Cable*1

3. Component Knowledge:

图片不存在

Button: A button can control the on/off state of a circuit. When the button is connected in the circuit and not pressed, the circuit is open. When pressed, the circuit closes; when released, it opens again. But why does it only conduct when pressed? This has to do with the internal structure of the button. Before pressing, current cannot pass from one end of the button to the other. When pressed, the metal piece inside the button connects both sides, allowing current to pass through.

The internal structure of a button is shown here: 图片不存在. Before pressing, pins 1 and 2 are connected, and pins 3 and 4 are also connected, but 1-3, 1-4, 2-3, and 2-4 are disconnected (not conducting). Only when the button is pressed do 1-3, 1-4, 2-3, or 2-4 become connected.

In circuit design, button switches are one of the most commonly used components.

Button Schematic:

图片不存在

What is Button Bouncing?

The switch circuit we imagine is "press the button - conducts immediately" and "press again - disconnects immediately," but in reality, this is not the case.

Buttons usually use mechanical elastic switches. At the moment the mechanical contacts open and close (usually around 10ms), a series of bounces occur due to the elastic action, causing the button switch to not conduct immediately when closed and not disconnect instantly when opened.

图片不存在

So How Do We Eliminate Button Bouncing?

There are two common debouncing methods: software and hardware. Here we focus on the convenient and simple software method.

We already know that the bounce time caused by elastic inertia is about 10ms. Using a delay command to postpone the execution of the command can achieve the debouncing effect.

So we added a 0.02-second delay in the code to implement button debouncing.

图片不存在

4. Project Wiring Diagram:

图片不存在

Note:

How to connect an LED

图片不存在

How to identify a five-color band 220Ω resistor and a five-color band 10KΩ resistor

图片不存在

图片不存在

5. Project Code:

//**********************************************************************
/* 
 * File name  : Small Desk Lamp
 * Description: Make a small desk lamp.
 */
#define PIN_LED    4
#define PIN_BUTTON 15
bool ledState = false;

void setup() {
  // Initialize the digital pin PIN_LED as an output.
  pinMode(PIN_LED, OUTPUT);
  pinMode(PIN_BUTTON, INPUT);
}

// The loop function repeats forever
void loop() {
  if (digitalRead(PIN_BUTTON) == LOW) {
    delay(20);
    if (digitalRead(PIN_BUTTON) == LOW) {
      reverseGPIO(PIN_LED);
    }
    while (digitalRead(PIN_BUTTON) == LOW);
  }
}

void reverseGPIO(int pin) {
  ledState = !ledState;
  digitalWrite(pin, ledState);
}
//**********************************************************************

6. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: press the button, the LED lights up; when the button is released, the LED stays on. Press the button again, the LED turns off; when the button is released, the LED stays off. Isn't it like a small desk lamp?

图片不存在

Project 15 Simulated Hourglass

1. Project Introduction:

In ancient times, people did not have electronic clocks, so they invented hourglasses to measure time. An hourglass has large capacity on both sides. One side is filled with fine sand, with a very small channel in the middle. When the hourglass is placed upright, the side with fine sand is on top. Due to gravity, the fine sand flows down through the channel to the other side. When all the sand has flowed to the bottom, flip it over. By recording the number of times this cycle repeats in a day, the next day you can know the approximate time by how many times the sand flows. In this lesson, we will use the ESP32 to control a tilt switch and LEDs to simulate an hourglass, making an electronic hourglass.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Tilt Switch*1 10KΩ Resistor*1
图片不存在 图片不存在 图片不存在 图片不存在
Red LED*4 220Ω Resistor*1 Jumper Wires (several) USB Cable*1

3. Component Knowledge:

图片不存在

A tilt switch is also called a digital switch or a ball switch, with a metal ball inside. It is used to detect slight tilting.

The principle is simple: when the switch is tilted at a certain angle, the ball inside rolls down and touches the two contacts connected to the external pins, thereby triggering the circuit. Otherwise, the ball stays away from the contacts, disconnecting the circuit.

Here we use the internal structure of the tilt switch to explain how it works, as shown below:

图片不存在

4. Project Wiring Diagram:

图片不存在

Note:

How to connect an LED

图片不存在

How to identify a five-color band 220Ω resistor and a five-color band 10KΩ resistor

图片不存在

图片不存在

5. Project Code:

//**********************************************************************
/* 
 * File name  : Tilt and LED
 * Description: Tilt switch and four LEDs simulate an hourglass.
 */
#define SWITCH_PIN  15  // Tilt switch connected to Pin15
byte switch_state = 0;
void setup()
{
     for(int i=16;i<20;i++)
  {
        pinMode(i, OUTPUT);
  } 
    pinMode(SWITCH_PIN, INPUT);
 for(int i=16;i<20;i++)
  {
    digitalWrite(i,0);
  } 
  Serial.begin(9600);
}
void loop()
{
switch_state = digitalRead(SWITCH_PIN); 
Serial.println(switch_state);
 if (switch_state == 0) 
 {
 for(int i=16;i<20;i++)
  {
    digitalWrite(i,1);
    delay(500);
  } 
  }
   if (switch_state == 1) 
  {
   for(int i=19;i>15;i--)
   {
    digitalWrite(i,0);
    delay(500);
   }
  }
}
//**********************************************************************************

6. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: tilt the breadboard to a certain angle, and the LEDs light up one by one. When returned to the previous angle, the LEDs turn off one by one. Just like an hourglass, as time passes, the sand flows out.

图片不存在

Project 16 Anti-Theft Alarm

1. Project Introduction:

A PIR (Passive Infrared) sensor measures the heat infrared (IR) rays emitted by moving objects. It can detect the movement of people, animals, and cars, triggering security alarms and lighting. They are used for motion detection and are ideal for security applications such as burglar alarms and security lighting systems. In this project, we will use the ESP32 to control a PIR sensor, a buzzer, and an LED to simulate a burglar alarm.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 PIR Sensor*1 NPN Transistor (S8050)*1
图片不存在 图片不存在 图片不存在 图片不存在
Active Buzzer*1 Red LED*1 220Ω Resistor*1 1KΩ Resistor*1
图片不存在 图片不存在 图片不存在
Dupont Wires (several) Jumper Wires (several) USB Cable*1

3. Component Knowledge:

PIR Sensor: It is a PIR sensor based on the pyroelectric effect. It can detect infrared rays emitted by the human body or animals. Combined with a Fresnel lens, it enables the sensor to detect from a farther and wider range. It primarily uses the RE200B-P sensor element. When a person or animal moves nearby, the module outputs a high level 1; otherwise, it outputs a low level 0. Note: This sensor can detect moving people, animals, and cars; stationary people, animals, and cars cannot be detected. The maximum detection distance is about 7 meters.

Note: The PIR sensor should be shielded from direct sunlight, car headlights, and incandescent lamps. It should also not face heat sources (such as radiators, heaters) or air conditioners to avoid false alarms caused by large changes in ambient temperature. It is also susceptible to RF radiation interference.

Sensor Technical Parameters:

Maximum Input Voltage: DC 5-15V

Maximum Operating Current: 50MA

Maximum Power: 0.3W

Static Current: <50uA

Operating Temperature: -20 ~ 85°C

Control Signal: Digital Signal (1/0)

Delay Time: Approximately 2.3 to 3 seconds

Sensing Angle: Less than 100 degrees cone angle

Maximum Detection Distance: About 7 meters

Sensor Schematic:

图片不存在

4. Project Wiring Diagram:

图片不存在

5. Project Code:

//**********************************************************************
/* 
 * File name  : Anti-Theft Alarm
 * Description: PIR sensor, buzzer, and LED simulate anti-theft alarm.
 */
#define buzzerPin   2   // Buzzer pin
#define ledPin   0     // LED pin
#define pirPin   15     // PIR motion sensor pin
byte pirStat = 0;   // PIR motion sensor state
void setup() {
 pinMode(buzzerPin, OUTPUT); 
 pinMode(ledPin, OUTPUT);    
 pinMode(pirPin, INPUT);     
}
void loop()
{
 pirStat = digitalRead(pirPin); 

 if (pirStat == HIGH)
 {            // If a person or moving animal is detected
   digitalWrite(buzzerPin, HIGH);  // Buzzer sounds
   digitalWrite(ledPin, HIGH);  // LED lights up
   delay(500);
   digitalWrite(buzzerPin, LOW);  // Buzzer stops
   digitalWrite(ledPin, LOW);  // LED turns off
   delay(500);
 } 
 else {  // Otherwise, no person or moving animal detected,
   digitalWrite(buzzerPin, LOW); // Turn off the buzzer
   digitalWrite(ledPin, LOW);  // Turn off the LED
 }
}
//*********************************************************************************

6. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: if the PIR sensor detects movement nearby, the buzzer will continuously sound the alarm, and the LED will flash continuously.

图片不存在

Project 17 OLED Display

1. Project Introduction:

In life, we can use display modules for various experiments. You can also DIY various small objects. For example, use a temperature sensor and a display to make a temperature tester, or use an ultrasonic module and a display to make a distance tester. Below, we will use the LCD_128X32_DOT module as a display, connecting it to the ESP32 control board. The ESP32 board will control the LCD_128X32_DOT display to show various English text, common symbols, and numbers.

Note: We have upgraded the LCD screen to a more commonly used OLED screen for accessories. Documentation is being updated. If you find the code does not run correctly, please contact customer service for repair.

2. Project Components:

图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 OLED Display*1
图片不存在 图片不存在
Male-to-Female Dupont Wires*4 USB Cable*1

3. Component Knowledge:

图片不存在

LCD_128X32_DOT: It is an LCD screen module with 128*32 pixels, and its driver chip is the ST7567A. The module uses IIC communication. It can display not only English letters and symbols but also Chinese characters and patterns. During use, you can also set it in the code to display English letters and symbols in different sizes.

LCD_128X32_DOT Schematic:

图片不存在

LCD_128X32_DOT Technical Parameters:

Display Pixels: 128*32 characters

Operating Voltage: DC 5V

Operating Current: 100mA (5V)

Module Optimal Operating Voltage: 5V

Brightness and contrast can be controlled via program commands.

4. Project Wiring Diagram:

图片不存在

5. Adding the LCD_128×32 Library:

This project code uses a library called "LCD_128×32". If you have already added the "LCD_128×32" library, skip this step. If you have not added it, please install it before starting. The steps to add a third-party library are as follows:

Open the Arduino IDE, click "Sketch" → "Include Library" → "Add .ZIP Library...". In the pop-up window, find the file named ..\library-files\arduino-c-windows\LCD_128X32.ZIP in that directory, select the LCD_128X32.ZIP file first, then click "Open".

图片不存在

图片不存在

6. Project Code:

//**********************************************************************************
/*
 * File name  : OLED 128*32
 * Description: OLED 128*32 displays strings
 */
//**********************************************************************************
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

Adafruit_SSD1306 display(128, 32, &Wire, -1);

void setup() {
  Serial.begin(9600);

  // Initialize I2C, display pins are SDA=21, SCL or SCK=22
  Wire.begin(21, 22);

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println("Initialization failed");
    return;
  }

  Serial.println("OLED initialized successfully");

  display.clearDisplay();
  display.setTextSize(1);  // Set font size
  display.setTextColor(SSD1306_WHITE); // Set text color (white)
  display.setCursor(0, 0); // Set cursor position (x, y)

  display.println("Hello world");
  display.println("0123456789");
  display.println("Using SoftI2C");
  display.display();

  Serial.println("Display content updated");
}

void loop() {
  // You can add the content you want to display here
  delay(1000);
}
//**********************************************************************************

7. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: the first line of the 128X32 LCD module displays "Hello World!", the second line displays "0123456789", and the third line displays "Using SoftI2C".

图片不存在

Project 18 Small Fan

1. Project Introduction:

In hot summer, we need electric fans to cool us down. In this project, we will use the ESP32 to control a DC motor and small fan blades to make a small electric fan.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 DC Motor*1 Breadboard Power Supply Module*1 6-cell AA Battery Holder*1
图片不存在 图片不存在 图片不存在 图片不存在 图片不存在
IC L293D*1 Fan Blades*1 Jumper Wires (several) AA Batteries (self-provided)*6 USB Cable*1

3. Component Knowledge:

图片不存在

L293D Chip: L293D is a DC motor driver IC that can be used to drive DC motors or stepper motors in some robot projects. It has 16 pins and can drive two DC motors simultaneously. Input voltage range: 4.5V ~ 36V, output current per channel: MAX 600mA. It can drive inductive loads, and its input terminals can be directly connected to the main control board, making it very convenient to control. When driving a small DC motor, it can directly control two motors and achieve forward and reverse rotation by simply changing the high/low levels at the input terminals. There are many motor driver boards on the market using the L293D chip, but of course we can also use it ourselves through simple connections.

L293D Pin Diagram:

图片不存在 | Pin Number | Pin Name | Description | | :--: | :--: | :--: | | 1 | Enable1 | This pin enables Input 1(2) and Input 2(7) | | 2 | In1 | Directly controls output 1 pin, controlled by digital circuit | | 3 | Out1 | Connect to one end of motor 1 | | 4 | 0V | Ground pin connected to circuit ground (0V) | | 5 | 0V | Ground pin connected to circuit ground (0V) | | 6 |Out2 | Connect to the other end of motor 1 | | 7 | In2 | Directly controls output 2 pin. Controlled by digital circuit | | 8 | +V motor | Connect to the pin of the voltage that drives the motor (4.5V to 36V) | | 9 | Enable2 | This pin enables Input 3(10) and Input 4(15) | | 10 | In3 | Directly controls output 3 pin. Controlled by digital circuit | | 11 | Out3 | Connect to one end of motor 2 | | 12 | 0V | Ground pin connected to circuit ground (0V) | | 13 | 0V | Ground pin connected to circuit ground (0V) | | 14 | Out4 | Connect to the other end of motor 2 | | 15 |In4 | Directly controls output 4 pin, controlled by digital circuit | | 16 | +V | Connect to +5V to enable IC functionality |

Breadboard Power Supply Module:

图片不存在

Description:

This module can conveniently provide 3.3V and 5V power to the breadboard. It has a DC2.1 input (DC7-12V) and also supports USB Type C power input.

Specifications:

Input Voltage: DC jack: 7-12V; Type C USB: 5V

Current: 3.3V: max 500mA; 5V: max 500mA

Maximum Power: 2.5W

Dimensions: 53mm x 26.3mm

Environmental Attributes: ROHS

Interface Description:

图片不存在

Motor Wiring Instructions:

Because the current batch of motors uses a standard connector that cannot be directly inserted into the breadboard, please use two Dupont wires inserted into the white connector to complete this experiment.

图片不存在

Schematic:

图片不存在

4. Project Wiring Diagram:

图片不存在

(Note: Connect the wires first, then install a small fan blade on the DC motor.)

5. Project Code:

//**********************************************************************************
/*
 * File name  : Small Fan
 * Description: Small fan rotates counterclockwise, stops, rotates clockwise, stops, loops.
 */
#define IN1 2  // L293D IN1 pin
#define IN2 15  // L293D IN2 pin
#define ENA_pwm 0  // L293D ENA-pwm pin
void setup()
{
pinMode(IN1,OUTPUT); // Set IN1 as OUTPUT
pinMode(IN2,OUTPUT); // Set IN2 as OUTPUT
ledcSetup(2, 1200, 8);// Set ledc channel 2, frequency 1200, PWM resolution 8, duty cycle 256.
ledcAttachPin(0, 2); // Bind ledc channel 2 to the specified ENA_pwm pin GPIO0 for output.
}
void loop()
{
// Rotate counterclockwise for 5 seconds
digitalWrite(IN1,LOW);
digitalWrite(IN2,HIGH);
ledcWrite(2, 250); // ledc channel 2 is bound to the specified ENA_pwm to output PWM value 250.
delay(5000);
// Stop 2s 
ledcWrite(2, 0); // ledc channel 2 is bound to the specified ENA_pwm to output PWM value 0.
delay(2000);
// Rotate clockwise for 5 seconds
digitalWrite(IN1,HIGH);
digitalWrite(IN2,LOW);
ledcWrite(2, 250); // ledc channel 2 is bound to the specified ENA_pwm to output PWM value 250.
delay(5000);
// Stop 2s
ledcWrite(2, 0); // ledc channel 2 is bound to the specified ENA_pwm to output PWM value 0.
delay(2000);
}
//********************************************************************************

6. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully, connect an external power supply. You will see: the small fan first rotates counterclockwise for 5 seconds, stops for 2 seconds, then rotates clockwise for 5 seconds, stops for 2 seconds, and repeats this pattern.

图片不存在

Project 19 Servo

1. Project Introduction:

A servo is a motor that can rotate very precisely. It is currently widely used in toy cars, remote control helicopters, airplanes, robots, and other fields. In this project, we will use the ESP32 to control the servo rotation.

2. Project Components:

图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Servo*1
图片不存在 图片不存在
Jumper Wires (several) USB Cable*1

3. Component Knowledge:

图片不存在

Servo: A servo is a positional servo driver, mainly composed of a housing, a circuit board, a coreless motor, gears, and a position detector. Its working principle is that the receiver or microcontroller sends a signal to the servo. Inside, there is a reference circuit that generates a reference signal with a period of 20ms and a width of 1.5ms. The obtained DC bias voltage is compared with the voltage of a potentiometer, and the voltage difference is output. The IC on the circuit board determines the direction of rotation, then drives the coreless motor to start rotating. Power is transmitted to the swing arm through reduction gears, while the position detector sends back a signal to determine whether the position has been reached. It is suitable for control systems where the angle needs to change continuously and be maintained. When the motor speed is constant, it drives the potentiometer to rotate through cascaded reduction gears, making the voltage difference 0 and the motor stops rotating. Generally, the rotation angle range of a servo is 0 to 180 degrees.

The pulse period for controlling the servo is 20ms, and the pulse width is 0.5ms ~ 2.5ms, corresponding to positions of -90° to +90°. Below is an example of a 180° servo:

图片不存在

Servos come in various specifications, but they all have three connecting wires: brown, red, and orange (different brands may have different colors). Brown is GND, red is power positive, and orange is the signal wire.

图片不存在

4. Project Wiring Diagram:

When powering the servo, note that the power supply voltage should be 3.3V-5V. Please ensure there are no errors when connecting the servo to the power supply.

图片不存在

5. Adding the ESP32Servo Library:

Install the third-party servo library via Library Manager: ESP32Servo. Skip if already installed.

图片不存在

6. Project Code:

//**********************************************************************
/*
 * File name  : Servo Rotation
 * Description: Control the servo to sweep
 */
#include <ESP32Servo.h>

Servo myservo;  // Create a servo object to control the servo

int posVal = 0;    // Variable to store servo position
int servoPin = 15; // Servo pin

void setup() {
  myservo.setPeriodHertz(50);           // Standard 50 Hz servo
  myservo.attach(servoPin, 500, 2500);  // Attach the servo on servoPin to the servo object
}
void loop() {

  for (posVal = 0; posVal <= 180; posVal += 1) { // From 0° to 180°
    // In 1-degree steps
    myservo.write(posVal);       // Tell the servo to go to position in variable 'posVal'
    delay(15);                   // Wait 15ms for the servo to reach the position
  }
  for (posVal = 180; posVal >= 0; posVal -= 1) { // From 180° to 0°
    myservo.write(posVal);       // Tell the servo to go to position in variable 'posVal'
    delay(15);                   // Wait 15ms for the servo to reach the position
  }
}
//********************************************************************************

6. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: the servo will rotate from 0° to 180°, then reverse direction to rotate from 180° to 0°, and repeat these actions in an infinite loop.

图片不存在

Project 20 Stepper Motor

1. Project Introduction:

A stepper motor has accurate positioning and is the most important component in industrial robots, 3D printers, large lathes, and other mechanical equipment. In this project, we will use the ESP32 to control a ULN2003 stepper motor driver board to drive a stepper motor.

2. Project Components:

图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 ULN2003 Stepper Motor Driver Board*1
图片不存在 图片不存在 图片不存在
Breadboard Power Supply Module*1 6-cell AA Battery Holder*1 Stepper Motor*1
图片不存在 图片不存在 图片不存在
Male-to-Female Dupont Wires (several) AA Batteries (self-provided)*6 USB Cable*1

3. Project Knowledge:

图片不存在

Stepper Motor: It is a motor controlled by a series of electromagnetic coils. It can rotate by precise degrees (or steps) as needed, allowing you to move it to an exact position and hold that position. It does this by energizing the coils inside the motor for very short periods, but you must keep the motor powered to hold it in the desired position. There are two basic types of stepper motors: unipolar and bipolar. In this project, we use the unipolar stepper motor 28-BYJ48.

图片不存在

28BYJ-48 Stepper Motor Working Principle:

A stepper motor is mainly composed of a stator and a rotor. The stator is the stationary part, as shown in the figure below where coils A, B, C, and D are wound. When the coil groups are energized, they generate a magnetic field; the rotor is the rotating part, the part in the middle of the stator below, with two poles being a permanent magnet.

Single-step 4-beat rotation principle: Initially, coil group A is energized, and the rotor poles face coil group A. Then coil group A is de-energized, coil group B is energized, and the rotor rotates clockwise to coil group B—the rotor has moved one step. B is de-energized, C is energized, the rotor moves to group C; C is de-energized, D is energized, the rotor moves to group D; group D is de-energized, group A is energized, the rotor moves to coil group A. In this way, the rotor has turned half a circle (180 degrees). Then repeat once more, B-C-D-A, the rotor returns to coil group A, and the rotor has completed one full rotation, totaling 8 steps. As shown in the diagram below, this is the single-beat rotation principle of the stepper motor: A - B - C - D - A ....

If you want the stepper motor to rotate counterclockwise, just reverse the beat order: D - C - B - A - D .....

图片不存在

Half-step 8-beat rotation principle: 8 beats use a single-double beat form: A - AB - B - BC - C - CD - D - DA - A ...... In this way, each beat rotates the rotor only half a step. For example, coil group A is energized, and the rotor turns to face coil group A. Then both A and B are energized together. The strongest magnetic field is in the middle of AB coil groups, so the rotor poles turn to the middle of the AB coil groups, i.e., a half-step clockwise rotation.

Stepper Motor Parameters:

The stepper motor we provide requires 32 steps for the rotor to complete one rotation. It also goes through a 1:64 reduction gear set to drive the output shaft, so the output shaft requires: 32 * 64 = 2048 steps per rotation.

Voltage 5V, 4-phase stepper motor, 4-beat mode step angle is 11.25°, 8-beat mode step angle is 5.625°, reduction ratio 1:64.

ULN2003 Stepper Motor Driver Board: The ULN2003 stepper motor driver converts weak signals into stronger control signals to drive the stepper motor.

The schematic below shows how to connect a unipolar stepper motor to the ESP32 pins using the ULN2003 stepper motor driver board interface, and how to use four TIP120 interfaces.

图片不存在

4. Project Wiring Diagram:

Set the power module jumper to 5V, connect the stepper motor driver board VCC to breadboard 5V, and GND to breadboard GND;

Connect the development board pin 5V to breadboard 5V, GND to breadboard GND, or power directly via USB.

Development Board Pin Motor Driver Board Pin
15 IN1
16 IN2
17 IN3
18 IN4

图片不存在

5. Project Code:

//**********************************************************************
/*
 * File name : Stepper Motor
 * Description: Use ULN2003 to drive a stepper motor.
 */
// Connect stepper motor driver interfaces
int outPorts[] = {15, 16, 17, 18};

void setup() {
  // Set pin outputs
  for (int i = 0; i < 4; i++) {
    pinMode(outPorts[i], OUTPUT);
  }
}

void loop()
{
  // Rotate one full circle
  moveSteps(true, 32 * 64, 3);
  delay(1000);
  // Rotate one full circle in the other direction
  moveSteps(false, 32 * 64, 3);
  delay(1000);
}

// Note: When ms is between 3 and 20, the motor rotates accurately
void moveSteps(bool dir, int steps, byte ms) {
  for (unsigned long i = 0; i < steps; i++) {
    moveOneStep(dir); // Rotate one step
    delay(constrain(ms,3,20));        // Control speed
  }
}

void moveOneStep(bool dir) {
  // Define a variable using four low bits to represent port states
  static byte out = 0x01;
  // Determine shift direction based on rotation direction
  if (dir) {  // Circular left shift
    out != 0x08 ? out = out << 1 : out = 0x01;
  }
  else {      // Circular right shift
    out != 0x01 ? out = out >> 1 : out = 0x08;
  }
  // Output signals to each port
  for (int i = 0; i < 4; i++) {
    digitalWrite(outPorts[i], (out & (0x01 << i)) ? HIGH : LOW);
  }
}

void moveAround(bool dir, int turns, byte ms){
  for(int i=0;i<turns;i++)
    moveSteps(dir,32*64,ms);
}
void moveAngle(bool dir, int angle, byte ms){
  moveSteps(dir,(angle*32*64/360),ms);
}
//********************************************************************************

6. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully, connect an external power supply. You will see: the four LEDs D1, D2, D3, D4 on the ULN2003 driver board light up. The stepper motor first rotates counterclockwise, then clockwise, and continues in a loop.

图片不存在

Project 21 Relay

1. Project Introduction:

In daily life, we generally use AC power to drive electrical devices, and sometimes we use switches to control appliances. If a switch is directly connected to an AC circuit, once leakage occurs, it is dangerous. For safety reasons, we have specially designed this relay module with NO (Normally Open) and NC (Normally Closed) terminals. In this lesson, we will learn about a special and useful switch: the relay module.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Relay Module*1 Red LED*1
图片不存在 图片不存在 图片不存在 图片不存在
Dupont Wires (several) USB Cable*1 220Ω Resistor*1 Jumper Wires (several)

3. Component Knowledge:

Relay: It primarily uses the HK4100F-DC 5V-SHC relay component. The relay has 3 terminals for external circuits: NO, COM, and NC (marked on the back).

Normally Open (NO): This pin is normally open unless a signal is provided to the relay module's signal pin. Therefore, the common contact pin disconnects its connection through the NC pin and establishes a connection through the NO pin.

Common Contact (COM): This pin is used to connect other modules/components, such as an LED.

LED: 图片不存在

Normally Closed (NC): This NC pin is connected through the COM pin to form a closed circuit. You can control the relay module via a development board like the ESP32 to switch between closed or open.

When the relay has no control signal, COM and NC are connected, and COM and NO are disconnected.

When controlling, connect G to the control board's GND, V to the control board's 5V, and S to the control board's digital pin. When the S signal pin is set to high, the relay turns on—COM and NC disconnect, and COM and NO connect. When the S signal pin is set to low, the relay turns off—COM and NC connect, and COM and NO disconnect.

  • Operating Voltage: 5V (DC)
  • Operating Current: ≤50MA
  • Maximum Power: 0.25W
  • Input Signal: Digital Signal
  • Contact Current: <3A

Relay Schematic:

图片不存在

4. Project Wiring Diagram:

图片不存在

5. Project Code:

//**********************************************************************************
/*
 * File name  : Relay
 * Description: Relay on and off.
 */
#define  Relay  15 // Define digital pin 15
void setup()
{
pinMode(Relay, OUTPUT); // Set "Relay" as "OUTPUT"
}
void loop()
{
digitalWrite(Relay, HIGH); // Turn on the relay
delay(1000); // Delay 1s
digitalWrite(Relay, LOW); // Turn off the relay
delay(1000); // Delay 1s
}
//**********************************************************************************

6. Project Phenomenon:

After the code is uploaded successfully and powered via the USB cable, you will see: the relay cycles on and off—on for 1 second (LED lights for 1 second), off for 1 second (LED off for 1 second). You can also hear the relay clicking and see the indicator light on the relay showing state changes.

图片不存在

Project 22 Dimmable Light

1. Project Introduction:

A potentiometer is a three-terminal resistor with a sliding or rotating contact that forms an adjustable voltage divider. It works by changing the position of the sliding contact across a uniform resistance. In a potentiometer, the entire input voltage is applied across the full length of the resistor, and the output voltage is the voltage value between the fixed contact and the sliding contact. In this project, we will learn to use the ESP32 to read the value of a potentiometer and combine it with an LED to make a dimmable light.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Adjustable Potentiometer*1 Red LED*1
图片不存在 图片不存在 图片不存在
220Ω Resistor*1 USB Cable*1 Jumper Wires (several)

3. Component Knowledge:

图片不存在

Adjustable Potentiometer: An adjustable potentiometer is a type of resistor and analog electronic component with two states (high and low levels). Different analog values have data states ranging linearly from 1 to 1024.

ADC: ADC is an electronic integrated circuit used to convert analog signals (such as voltage) into digital or binary form consisting of 1s and 0s. The ADC range on our ESP32 is 12-bit, meaning the resolution is 2^12=4096. This means a range (3.3V) is divided equally into 4096 parts, and the analog value range corresponds to the ADC value. Therefore, the more bits the ADC has, the denser the analog divisions, and the higher the final conversion precision.

图片不存在

Section 1: Analog values in the range 0V—(3.3/4095)V correspond to digital 0;

Section 2: Analog values in the range (3.3/4095)V—2*(3.3/4095)V correspond to digital 1;

......

The following analog values are divided accordingly. The conversion formula is as follows:

图片不存在

DAC: The reverse of this process requires a DAC (Digital-to-Analog Converter). Digital I/O ports can output high and low levels (0 or 1), but not intermediate voltage values—this is where DAC is useful. The ESP32 has two 8-bit DAC output pins, GPIO25 and GPIO26, which can divide VCC (3.3V here) into 2^8=256 parts. For example, when the digital value is 1, the output voltage is 3.3/256×1V; when the digital value is 128, the output voltage is 3.3/256 ×128=1.65V. The higher the DAC precision, the higher the output voltage precision.

The conversion formula is as follows:

图片不存在

ADC on the ESP32 Board:

The ESP32 has 16 pins that can be used to measure analog signals. The GPIO pin sequence numbers and analog pin definitions are shown in the table below:

图片不存在

DAC on the ESP32 Board:

图片不存在

4. Reading the Potentiometer's ADC Value, DAC Value, and Voltage Value:

We connect the potentiometer to the ESP32's analog I/O port to read the potentiometer's ADC value, DAC value, and voltage value. Please refer to the wiring diagram below:

图片不存在

//**********************************************************************************
/*  
 * File name   : Reading Potentiometer Analog Value
 * Description: Basic usage of ADC, DAC, and voltage
 */
#define PIN_ANALOG_IN  36  // Potentiometer pin

void setup() {
  Serial.begin(115200);
}

// In loop(), use the analogRead() function to get the ADC value,
// then use the map() function to convert the value to an 8-bit DAC value.
// Input/output voltage is calculated by the formula below,
// and the information is finally printed.

void loop() {
  int adcVal = analogRead(PIN_ANALOG_IN);
  int dacVal = map(adcVal, 0, 4095, 0, 255);
  double voltage = adcVal / 4095.0 * 3.3;
  Serial.printf("ADC Val: %d, \t DAC Val: %d, \t Voltage: %.2fV\n", adcVal, dacVal, voltage);
  delay(200);
}
//**********************************************************************************
Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, open the serial monitor and set the baud rate to 115200. You will see: the serial monitor window prints the potentiometer's ADC value, DAC value, and voltage value. When you rotate the potentiometer knob, the ADC value, DAC value, and voltage value change.

图片不存在

5. Dimmable Light Wiring Diagram:

In the previous step, we read the potentiometer's ADC value, DAC value, and voltage value. Now we need to convert the potentiometer's ADC value to LED brightness to make an adjustable brightness light. See the wiring diagram below:

图片不存在

6. Project Code:

//**********************************************************************************
/*  
 * File name  : Dimmable Light
 * Description: Control LED brightness via potentiometer.
 */
#define PIN_ANALOG_IN    36  // Potentiometer pin
#define PIN_LED     15  // LED pin
#define CHAN            0
void setup() {
  ledcSetup(CHAN, 1000, 12);
  ledcAttachPin(PIN_LED, CHAN);
}

void loop() {
  int adcVal = analogRead(PIN_ANALOG_IN); // Read ADC
  int pwmVal = adcVal;        // Remap adcVal to pwmVal
  ledcWrite(CHAN, pwmVal);    // Set pulse width
  delay(10);
}
//**********************************************************************************
7. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: rotate the potentiometer knob, and the LED brightness changes accordingly.

图片不存在

Project 23 Flame Alarm

1. Project Introduction:

Fire is a terrible disaster. Fire alarm systems are very useful in homes, commercial buildings, and factories. In this project, we will use the ESP32 to control a flame sensor, a buzzer, and an LED to simulate a fire alarm device. This is a meaningful maker activity.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Flame Sensor*1 Red LED*1
图片不存在 图片不存在 图片不存在 图片不存在
Active Buzzer*1 220Ω Resistor*1 10KΩ Resistor*1 Jumper Wires (several)
图片不存在 图片不存在 图片不存在
NPN Transistor (S8050)*1 1kΩ Resistor*1 USB Cable*1

3. Component Knowledge:

图片不存在

Flame Sensor (Infrared Receiving Transistor): A flame emits a certain amount of IR light, which is invisible to the human eye, but our infrared receiving transistor can detect it and alert the microcontroller (such as the ESP32) that a fire has been detected. The infrared receiving transistor can detect flames and convert the flame brightness into a fluctuating level signal. The short pin of the infrared receiving transistor is the negative terminal, and the other long pin is the positive terminal. We should connect the short pin (negative) to 5V, and connect the long pin (positive) to an analog pin, a resistor, and GND. As shown below:

图片不存在

Note: The flame sensor should be shielded from direct sunlight, car headlights, and incandescent lamps. It should also not face heat sources (such as radiators, heaters) or air conditioners to avoid false alarms caused by large changes in ambient temperature. It is also susceptible to RF radiation interference.

4. Reading the Flame Sensor's ADC Value, DAC Value, and Voltage Value:

We first use a simple code to read the flame sensor's ADC value, DAC value, and voltage value and print them. Please refer to the wiring diagram below:

图片不存在

//**********************************************************************************
/*  
 * File name  : Reading Flame Sensor Analog Value
 * Description: Basic usage of ADC, DAC, and voltage
 */
#define PIN_ANALOG_IN  36  // Flame sensor pin

void setup() {
  Serial.begin(115200);
}

// In loop(), use the analogRead() function to get the ADC value,
// then use the map() function to convert the value to an 8-bit DAC value.
// Input/output voltage is calculated by the formula below,
// and the information is finally printed.

void loop() {
  int adcVal = analogRead(PIN_ANALOG_IN);
  int dacVal = map(adcVal, 0, 4095, 0, 255);
  double voltage = adcVal / 4095.0 * 3.3;
  Serial.printf("ADC Val: %d, \t DAC Val: %d, \t Voltage: %.2fV\n", adcVal, dacVal, voltage);
  delay(200);
}
//**********************************************************************************
Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, open the serial monitor and set the baud rate to 115200. You will see: the serial monitor window prints the ADC value, DAC value, and voltage value read by the flame sensor. When a flame approaches the flame sensor, the ADC value, DAC value, and voltage value increase; conversely, they decrease.

图片不存在

5. Fire Alarm Wiring Diagram:

Next, we will use the flame sensor, buzzer, and LED to make an interesting project—a fire alarm device. When the flame sensor detects a flame, the LED flashes and the buzzer alarms.

图片不存在

6. Project Code:

(Note: The threshold value 500 in the code can be re-set according to actual conditions)

//**********************************************************************************
/*  
 * File name : Flame Alert
 * Description: Control buzzer and LED via flame sensor.
 */
#define PIN_ADC0      36  // Flame sensor pin
#define PIN_LED       15  // LED pin
#define PIN_BUZZER    4  // Buzzer pin

void setup() {
  pinMode(PIN_LED, OUTPUT);
  pinMode(PIN_BUZZER, OUTPUT);
  pinMode(PIN_ADC0, INPUT);
}

void loop() {
  int adcVal = analogRead(PIN_ADC0); // Read the flame sensor's ADC value
  if (adcVal >= 500) {
    digitalWrite (PIN_BUZZER, HIGH); // Buzzer sounds
    digitalWrite(PIN_LED, HIGH); // Light up LED
    delay(500); // Delay 0.5s
    digitalWrite (PIN_BUZZER, LOW);
    digitalWrite(PIN_LED, LOW); // Turn off LED
    delay(500); // Delay 0.5s
  }
 else
 {
    digitalWrite(PIN_LED, LOW);  // Turn off LED
    digitalWrite (PIN_BUZZER, LOW); // Turn off buzzer
  }
}
//**********************************************************************************
7. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: when the flame sensor detects a flame, the LED flashes and the buzzer alarms; otherwise, the LED stays off and the buzzer stays silent.

图片不存在

Project 24 Small Night Light

1. Project Introduction:

Sensors or components are everywhere in our daily lives. For example, some public street lights automatically turn on at night and turn off during the day. Why? In fact, these all use a photosensitive component that can sense the intensity of ambient light. At night, when the outdoor brightness decreases, the street lights automatically turn on; during the day, the street lights automatically turn off. The principle behind this is very simple. In this experiment, we use the ESP32 to control an LED to replicate the effect of a street light.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Photoresistor*1 Red LED*1
图片不存在 图片不存在 图片不存在 图片不存在
220Ω Resistor*1 10KΩ Resistor*1 Jumper Wires (several) USB Cable*1

3. Component Knowledge:

图片不存在

Photoresistor: It is a light-sensitive resistor. The principle is that the resistance of the photoresistor surface decreases when it receives brightness (light). The resistance of the photoresistor changes with the intensity of the detected ambient light. With this property, we can use a photoresistor to detect light intensity. The photoresistor and its electronic symbol are as follows:

图片不存在

The circuit below is used to detect changes in the photoresistor's resistance:

图片不存在

In the above circuit, when the resistance of the photoresistor changes due to variations in light intensity, the voltage between the photoresistor and resistor R2 also changes. Therefore, by measuring this voltage, we can obtain the light intensity. This project uses the circuit on the left in the figure above for wiring.

4. Reading the Photoresistor's ADC Value, DAC Value, and Voltage Value:

We first use a simple code to read the photoresistor's ADC value, DAC value, and voltage value and print them. Please refer to the wiring diagram below:

图片不存在

//**********************************************************************************
/*  
 * File name  : Reading Photosensitive Sensor Analog Value
 * Description: Basic usage of ADC
 */
#define PIN_ANALOG_IN  36  // Photosensitive sensor pin

void setup() {
  Serial.begin(115200);
}

// In loop(), use the analogRead() function to get the ADC value,
// then use the map() function to convert the value to an 8-bit DAC value.
// Input/output voltage is calculated by the formula below,
// and the information is finally printed.

void loop() {
  int adcVal = analogRead(PIN_ANALOG_IN);
  int dacVal = map(adcVal, 0, 4095, 0, 255);
  double voltage = adcVal / 4095.0 * 3.3;
  Serial.printf("ADC Val: %d, \t DAC Val: %d, \t Voltage: %.2fV\n", adcVal, dacVal, voltage);
  delay(200);
}
//**********************************************************************************
Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, open the serial monitor and set the baud rate to 115200. You will see: the serial monitor window prints the ADC value, DAC value, and voltage value read by the photoresistor. When you gradually reduce the light intensity in the photoresistor's environment, the ADC value, DAC value, and voltage value gradually increase; conversely, they gradually decrease.

图片不存在

5. Light-Controlled Lamp Wiring Diagram:

We previously made a small dimmable light; now we will make a light-controlled lamp. The principle is the same—reading the sensor's analog value via the ESP32 and adjusting the LED brightness.

图片不存在

6. Project Code:

//**********************************************************************************
/*  
 * File name  : Night Light
 * Description: Control LED brightness via photosensitive sensor.
 */
#define PIN_ANALOG_IN    36  // Photosensitive sensor pin
#define PIN_LED     15  // LED pin
#define CHAN            0
#define LIGHT_MIN       372
#define LIGHT_MAX       2048
void setup() {
  ledcSetup(CHAN, 1000, 12);
  ledcAttachPin(PIN_LED, CHAN);
}

void loop() {
  int adcVal = analogRead(PIN_ANALOG_IN); // Read ADC
  int pwmVal = map(constrain(adcVal, LIGHT_MIN, LIGHT_MAX), LIGHT_MIN, LIGHT_MAX, 0, 4095);  // Remap adcVal to pwmVal
  ledcWrite(CHAN, pwmVal);    // Set pulse width
  delay(10);
}
//**********************************************************************************
7. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: when the light intensity in the photoresistor's environment decreases, the LED becomes brighter; conversely, the LED becomes dimmer.

图片不存在

Project 25 Human Body Induction Light

1. Project Introduction:

Human body induction lights are generally used in dark corridor areas. With the development of technology, human body induction lights are very common in our real lives—used in apartment corridors, bedrooms, underground garages, bathrooms, and other areas. Real-life human body induction lights are generally composed of a PIR sensor, lights, photoresistors, etc.

In this project, we will learn how to use a PIR sensor, LED, and photoresistor to make a human body induction light.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Photoresistor*1 Red LED*1
图片不存在 图片不存在 图片不存在 图片不存在
220Ω Resistor*1 10KΩ Resistor*1 Jumper Wires (several) USB Cable*1
图片不存在 图片不存在
PIR Sensor*1 Dupont Wires (several)

3. Project Wiring Diagram:

图片不存在

4. Project Code:

//**********************************************************************************
/*  
 * File name  : Human Body Induction Light
 * Description: Control LED via photosensitive sensor and PIR motion sensor.
 */
#define PIN_ADC0  36   // Photosensitive sensor pin
#define PIN_LED   4  // LED pin
#define pirPin   15     // PIR sensor pin
byte pirStat = 0;   // PIR sensor state
void setup() {
  Serial.begin(115200);
  pinMode(PIN_LED, OUTPUT);
  pinMode(PIN_ADC0, INPUT);
  pinMode(pirPin, INPUT);
}

void loop() {
  int adcVal = analogRead(PIN_ADC0); // Read the photosensitive sensor's ADC value
  pirStat = digitalRead(pirPin); // Read the PIR sensor value
  if (adcVal >= 2000) {
      if (pirStat == HIGH){
         digitalWrite(PIN_LED, HIGH);// Light up LED
         } 
      else{
         digitalWrite(PIN_LED, LOW);// Turn off LED   
        }
  }
   else{
      digitalWrite(PIN_LED, LOW);// Turn off LED
      }
}
//**********************************************************************************
5. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: when you cover the photosensitive part of the photoresistor with your hand to simulate darkness, and then wave your other hand in front of the PIR sensor, the LED lights up. If the photosensitive part is not covered and you wave your hand in front of the PIR sensor, the LED stays off.

图片不存在

Project 26 Joystick Controlled RGB Light

1. Project Introduction:

A joystick module is a component with two analog inputs and one digital input. It is widely used in gaming controls, robot controls, drone controls, and other fields. In this project, we use the ESP32 and a joystick module to control an RGB LED. This way, you can gain a deeper understanding of the joystick module's principles and operation in practice.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Joystick Module*1 RGB LED*1
图片不存在 图片不存在 图片不存在 图片不存在
220Ω Resistor*3 Jumper Wires (several) USB Cable*1 Male-to-Female Dupont Wires*5

3. Component Knowledge:

图片不存在

Joystick Module: It primarily uses a PS2 joystick component. The joystick module has 3 signal pins, simulating 3D space. The pins of the joystick module are GND, VCC, and signal pins (VRx, VRy, SW). Signal pins X and Y simulate the X-axis and Y-axis of space. During control, the module's X and Y signal pins are connected to the control board's analog ports. By controlling the 2 analog input values, you can control the coordinates of an object in the X and Y axes. The signal pin SW simulates the Z-axis of space. It is generally connected to a digital pin and used as a button.

VCC connects to the control board's power output V/VCC (3.3/5V), and GND connects to the control board's G/GND. In the original state, the voltage reading is approximately 1.65V/2.5V. For the X-axis direction, as you gradually move in the direction of the arrow, the voltage reading increases up to the maximum voltage; as you move in the opposite direction, the voltage reading decreases down to the minimum voltage. For the Y-axis direction, as you gradually press in the direction of the arrow on the module, the voltage reading increases up to the maximum voltage; as you press in the opposite direction, the voltage reading decreases down to the minimum voltage. For the Z-axis direction, signal pin B is connected to a digital pin. In the original state, it outputs 0; when pressed, it outputs 1. In this way, we can read two analog values and one digital pin's high/low level state to determine the working state of the joystick on the module.

Module Parameters:

  • Input Voltage: DC 3.3V ~ 5V
  • Output Signal: X/Y dual-axis analog values + Z-axis digital signal
  • Applicable Range: Suitable for controlling point coordinate movement in a plane, dual-degree-of-freedom servo control, etc.
  • Product Features: Beautiful appearance, excellent joystick feel, simple operation, fast response, long service life.

4. Reading the Joystick Module Values:

We must use the ESP32's analog I/O ports to read the values from the joystick module's X/Y pins, and use a digital I/O port to read the button's digital signal. Please wire according to the diagram below (due to accessory changes, B=SW in the figure below):

图片不存在

//**********************************************************************************
/*  
 * File name  : Reading Joystick Values
 * Description: Read data from the joystick module.
 */
int xyzPins[] = {36, 39, 14};   // Pins x, y, z
void setup() {
  Serial.begin(115200);
  pinMode(xyzPins[0], INPUT); // X axis
  pinMode(xyzPins[1], INPUT); // Y axis
  pinMode(xyzPins[2], INPUT_PULLUP);   // Z axis is a button
}

// In loop(), use analogRead() to read the X and Y axis values
// and digitalRead() to read the Z axis value, then display them.

void loop() {
  int xVal = analogRead(xyzPins[0]);
  int yVal = analogRead(xyzPins[1]);
  int zVal = digitalRead(xyzPins[2]);
  Serial.println("X,Y,Z: " + String(xVal) + ", " +  String(yVal) + ", " + String(zVal));
  delay(500);
}
//**********************************************************************************
Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, open the serial monitor and set the baud rate to 115200. You will see: the serial monitor window prints the joystick's current analog values and digital values. Moving the joystick or pressing the joystick cap will change the analog and digital values in the serial monitor window.

图片不存在

图片不存在

5. Joystick Module Controlling RGB Wiring Diagram:

We just read the joystick module values; now we need to use the joystick module and RGB to do something. Connect as shown below:

图片不存在

6. Project Code:

//**********************************************************************************
/*  
 * File name  : Joystick Controlled Light
 * Description: Control RGB to light up different colors via joystick.
 */
int x_Pin = 36;   // X pin
int y_Pin = 39;   // Y pin
int z_Pin = 14;   // Z pin
int ledPins[] = {4, 0, 2};    // Define red, green, blue pins
const byte chns[] = {0, 1, 2};        // Define PWM channels

void setup() {
  pinMode(x_Pin, INPUT); // X axis
  pinMode(y_Pin, INPUT); // Y axis
  pinMode(z_Pin, INPUT_PULLUP);   // Z axis is a button
  for (int i = 0; i < 3; i++) {   // Set up PWM channels, 1KHz, 8-bit
    ledcSetup(chns[i], 1000, 8);
    ledcAttachPin(ledPins[i], chns[i]);
  }
}

// In loop(), use analogRead() to read the X and Y axis values
// and digitalRead() to read the Z axis value, then display them.

void loop() {
  int xVal = analogRead(x_Pin);
  int yVal = analogRead(y_Pin);
  int zVal = digitalRead(z_Pin);
  if (xVal < 1000){
     ledcWrite(chns[0], 255); // Common cathode LED, high level turns on the LED.
     ledcWrite(chns[1], 0);
     ledcWrite(chns[2], 0);
   }
  else if (xVal > 3000){
     ledcWrite(chns[0], 0); 
     ledcWrite(chns[1], 255);
     ledcWrite(chns[2], 0);
   }
  else if (yVal < 1000){
     ledcWrite(chns[0], 0);
     ledcWrite(chns[1], 0);
     ledcWrite(chns[2], 255);
   }
  else if (yVal > 3000){
     ledcWrite(chns[0], 255); 
     ledcWrite(chns[1], 255);
     ledcWrite(chns[2], 255);
   }
}
//**********************************************************************************
7. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: ① If the joystick is moved to the far left in the X direction, the RGB light turns red; ② If the joystick is moved to the far right in the X direction, the RGB light turns green; ③ If the joystick is moved to the top in the Y direction, the RGB light turns white; ④ If the joystick is moved to the bottom in the Y direction, the RGB light turns blue.

图片不存在

图片不存在

Project 27 Temperature and Humidity Meter

1. Project Introduction:

In winter, the air humidity is very low, meaning the air is very dry. Combined with the cold, human skin can become excessively dry and crack. So you need a humidifier to increase the humidity in your home's air. But how do you know when the air is too dry? You need a device to detect air humidity. In this lesson, we will learn how to use a temperature and humidity sensor. We use a temperature and humidity sensor to make a thermo-hygrometer, combined with an LCD 128X32 DOT to display temperature and humidity values.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 OLED Display*1 Temperature and Humidity Sensor*1
图片不存在 图片不存在
Dupont Wires (several) USB Cable*1

3. Component Knowledge:

图片不存在

Temperature and Humidity Sensor: It is a composite sensor containing calibrated digital signal output for temperature and humidity. Its accuracy is ±5%RH for humidity, ±2℃ for temperature. Range: humidity 20-90%RH, temperature 0~50℃. The sensor uses dedicated digital module acquisition technology and temperature/humidity sensing technology, ensuring high reliability and excellent long-term stability. It includes a resistive humidity sensing element and an NTC temperature measuring element, making it very suitable for temperature and humidity measurement applications where accuracy and real-time performance requirements are not high. Operating voltage range: 3.3V-5.5V.

The temperature and humidity sensor has three pins: VCC, GND, and S. S is the data output pin. It uses serial communication.

Different batches may also have three pins: +, -, and OUT. + connects to power, - connects to GND, and OUT is the data output pin.

Temperature and Humidity Sensor Single-Bus Format Definition:

Name Single-Bus Format Definition
Start Signal The microprocessor pulls the data bus (SDA) low for at least 18ms (must not exceed 30ms) to signal the sensor to prepare data.
Response Signal The sensor pulls the data bus (SDA) low for 83µs, then high for 87µs in response to the host's start signal.
Humidity The high byte of humidity is the integer part, and the low byte is the decimal part.
Temperature The high byte of temperature is the integer part, and the low byte is the decimal part. If bit 8 of the temperature low byte is 1, the temperature is negative; otherwise, it is positive.
Checksum Checksum = humidity high byte + humidity low byte + temperature high byte + temperature low byte

Temperature and Humidity Sensor Data Timing Diagram:

After the user host (MCU) sends a start signal, the temperature and humidity sensor switches from low-power mode to high-speed mode. After the host start signal ends, the sensor sends a response signal, outputs 40 bits of data, and triggers a data acquisition. Signal transmission is shown in the figure.

图片不存在

The temperature and humidity sensor can easily add temperature and humidity data to your DIY electronics projects. It is perfect for remote weather stations, home environment control systems, and farm or garden monitoring systems.

Temperature and Humidity Sensor Parameters: - Operating Voltage: +5V - Temperature Range: 0-50 °C, Accuracy: ±2 °C - Humidity Range: 20-90% RH, Accuracy: ±5% RH - Digital Interface

Temperature and Humidity Sensor Schematic:

图片不存在

4. Reading Temperature and Humidity Values:

图片不存在

How to Add the xht11 Library:

This project code uses a library called "xht11". If you have already added the "xht11" library, skip this step. If you have not added it, please add it before starting. The steps to add a third-party library are as follows:

Open the Arduino IDE, click "Sketch" → "Include Library" → "Add .ZIP Library...". In the pop-up window, find the file named ..\library-files\arduino-c-windows\xht11.ZIP in that directory, select the xht11.ZIP file first, then click "Open".

图片不存在

图片不存在

//**********************************************************************************
/*
 * File name  : Thermo-Hygrometer
 * Description: LCD displays temperature and humidity values.
 */
#include "xht11.h"
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>


// Temperature and humidity sensor out pin connects to 13
xht11 xht(13);
unsigned char dht[4] = {0, 0, 0, 0};    // Only receive the first 32 bits of data, not the checksum

Adafruit_SSD1306 display(128, 32, &Wire, -1);

void setup() 
{
  Serial.begin(9600);

 // Initialize I2C, display pins are SDA=21, SCL or SCK=22
  Wire.begin(21, 22);

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println("Initialization failed");
    return;
  }
  Serial.println("setup done");
}

char string[10];

// LCD displays humidity and temperature values
void loop() 
{

  if (xht.receive(dht))  // When data is received
  {
    display.clearDisplay();
    display.setTextSize(2);  // Set font size
    display.setTextColor(SSD1306_WHITE); // Set text color (white)

    display.setCursor(2, 2); // Set cursor position (x, y)
    display.print("temp:");
    display.setCursor(60, 2); 
    display.print(dht[2]);
    display.setCursor(90, 2); 
    display.print("C");

    display.setCursor(2, 30); // Set cursor position (x, y)
    display.print("humd:");
    display.setCursor(60, 30); 
    display.print(dht[0]);
    display.setCursor(90, 30); 
    display.print("%");

    display.display();

    // Serial output
    Serial.print(dht[2]);Serial.print(" C   ");
    Serial.print(dht[0]);Serial.println(" %");
  }

  delay(200);
}
//**********************************************************************************
Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, open the serial monitor and set the baud rate to 115200. You will see: the serial monitor window prints the current temperature and humidity data for the environment, as shown below.

图片不存在

5. Temperature and Humidity Meter Wiring Diagram:

Now we will use the LCD_128X32_DOT to print the temperature and humidity sensor's values. We will see the corresponding values on the LCD_128X32_DOT screen. Let's start this project. Please wire according to the diagram below:

图片不存在

6. Project Code:

You have already added the xht11 and LCD_128×32 libraries previously, so there is no need to add them again. If not added, you need to add the xht11 and LCD_128×32 libraries. For the xht11 library, refer to the method above in this project. For the LCD_128×32 library, refer to the method in Project 17 OLED Display.

//**********************************************************************************
/*
 * File name  : Thermo-Hygrometer
 * Description: LCD displays temperature and humidity values.
 */
#include "xht11.h"
#include "lcd128_32_io.h"

// gpio13
xht11 xht(13);
unsigned char dht[4] = {0, 0, 0, 0};// Only receive the first 32 bits of data, not the checksum

lcd lcd(21, 22); // Create LCD128*32 pins, sda->21, scl->22

void setup() {
  lcd.Init(); // Initialize
  lcd.Clear();  // Clear screen
}
char string[10];

// LCD displays humidity and temperature values
void loop() {
  if (xht.receive(dht)) { // Returns true when correctly selected
    }
  lcd.Cursor(0,0); // Set display position
  lcd.Display("Temper:"); // Set display
  lcd.Cursor(0,8);
  lcd.DisplayNum(dht[2]);
  lcd.Cursor(0,11);
  lcd.Display("C");
  lcd.Cursor(2,0); 
  lcd.Display("humid:");
  lcd.Cursor(2,8);
  lcd.DisplayNum(dht[0]);
  lcd.Cursor(2,11);
  lcd.Display("%");
  delay(200);
}
//**********************************************************************************
7. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: the LCD 128X32 DOT screen displays the temperature and humidity values detected by the sensor in the environment.

图片不存在

Project 28 Distance Meter

1. Project Introduction:

The HC-SR04 ultrasonic sensor is a very affordable distance sensor, primarily used for obstacle avoidance in various robot projects. It is also used for water level sensors and even as a parking sensor. We treat the ultrasonic sensor like a bat's eyes—in the dark, bats can still identify objects and directions ahead through ultrasonic waves. In this project, we use the ESP32 to control the ultrasonic sensor and LEDs to simulate an ultrasonic distance meter.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Ultrasonic Sensor*1 Dupont Wires (several)
图片不存在 图片不存在 图片不存在 图片不存在
Red LED*4 220Ω Resistor*4 Jumper Wires (several) USB Cable*1

3. Component Knowledge:

HC-SR04 Ultrasonic Sensor: Like bats, it uses sonar to determine distance to objects, providing accurate non-contact range detection with high precision and stable readings. Its operation is not affected by sunlight or black materials (acoustically soft materials like cloth are difficult to detect, similar to a precision camera). It comes with an ultrasonic transmitter and receiver.

图片不存在

In front of the ultrasonic sensor are two metal cylinders—these are the transducers. Transducers convert mechanical energy into electrical signals. In the ultrasonic sensor, there is a transmitting transducer and a receiving transducer. The transmitting transducer converts electrical signals into ultrasonic pulses, and the receiving transducer converts reflected ultrasonic pulses back into electrical signals. If you look at the back of the ultrasonic sensor, you will see an IC behind the transmitting transducer. This is the IC that controls the transmitting transducer. There is also an IC behind the receiving transducer—a four-op-amp that amplifies the signal generated by the receiving transducer into a signal strong enough to transmit to the microcontroller.

Timing Diagram:

The figure shows the timing diagram of the HC-SR04. To start a measurement, the SR04's Trig must receive a high (5V) pulse of at least 10µs. This triggers the sensor to emit 8 cycles of 40kHz ultrasonic pulses and wait for reflected ultrasonic pulses. When the sensor detects the ultrasonic wave from the receiver, it sets the Echo pin high (5V) for a duration (width) proportional to the distance. To obtain the distance, measure the width of the Echo pin.

图片不存在

Time = Echo pulse width, in µs (microseconds)

Distance in cm = Time / 58

Distance (inches) = Time / 148

4. Reading Ultrasonic Sensor Distance Values

We will start with a simple ultrasonic distance measurement and print the measured distance.

图片不存在

The HC-SR04 ultrasonic sensor has four pins: Vcc, Trig, Echo, and GND. The Vcc pin provides power for generating ultrasonic pulses; connect to Vcc/+5V. The GND pin connects to ground/GND. The Trig pin is where the control board sends the signal to trigger the ultrasonic pulse. The Echo pin is where the ultrasonic sensor sends information about the duration of the ultrasonic pulse's travel time back to the control board. Wire as shown below:

图片不存在

//**********************************************************************************
/*  
 * File name  : Ultrasonic Distance Measurement
 * Description: Use ultrasonic module to measure distance.
 */
const int TrigPin = 13; // Define TrigPin
const int EchoPin = 14; // Define EchoPin.
int duration = 0; // Define initial value of duration as 0
int distance = 0;// Define initial value of distance as 0
void setup() 
{
  pinMode(TrigPin , OUTPUT); // Set trigPin as output mode
  pinMode(EchoPin , INPUT); // Set echoPin as input mode
  Serial.begin(115200);  // Set serial monitor baud rate to 115200.
}
void loop()
{
 // Make trigPin output high for 10µs to trigger HC_SR04 
  digitalWrite(TrigPin , HIGH);
  delayMicroseconds(10);
  digitalWrite(TrigPin , LOW);
  // Wait for HC-SR04 to return high, measure this waiting time
  duration = pulseIn(EchoPin , HIGH);
  // Calculate distance based on time
  distance = (duration/2) / 28.5 ;
  Serial.print("Distance: ");
  Serial.print(distance); // Print distance value via serial
  Serial.println("cm");
  delay(300); // Wait 300ms.
}
//**********************************************************************************

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, open the serial monitor and set the baud rate to 115200. You will see: the serial monitor window prints the distance value between the ultrasonic sensor and the object.

图片不存在

5. Ultrasonic Distance Meter Wiring Diagram:

Next, we will use the ESP32 to control the ultrasonic sensor and 4 LEDs to simulate an ultrasonic distance meter. Wire as shown below:

图片不存在

6. Project Code:

//**********************************************************************************
/*  
 * File name  : Ultrasonic Distance Meter
 * Description: Four LEDs controlled by ultrasonic distance measurement.
 */
const int TrigPin = 13;    // Define TrigPin
const int EchoPin = 14;    // Define EchoPin.
const int PIN_LED1 = 4;    // Define PIN_LED1
const int PIN_LED2 = 0;    // Define PIN_LED2
const int PIN_LED3 = 2;    // Define PIN_LED3
const int PIN_LED4 = 15;    // Define PIN_LED4
int duration = 0;    // Define initial value of duration as 0
int distance = 0;   // Define initial value of distance as 0
void setup() 
{
  pinMode(TrigPin , OUTPUT); // Set trigPin as output mode
  pinMode(EchoPin , INPUT); // Set echoPin as input mode
  pinMode(PIN_LED1 , OUTPUT);  // Set PIN_LED1 as output mode
  pinMode(PIN_LED2 , OUTPUT);  // Set PIN_LED2 as output mode
  pinMode(PIN_LED3 , OUTPUT);  // Set PIN_LED3 as output mode
  pinMode(PIN_LED4 , OUTPUT);  // Set PIN_LED4 as output mode
  Serial.begin(115200);  // Set serial monitor baud rate to 115200.
}
void loop()
{
// Make trigPin output high for 10µs to trigger HC_SR04  
  digitalWrite(TrigPin , HIGH);
  delayMicroseconds(10);
  digitalWrite(TrigPin , LOW);
  // Wait for HC-SR04 to return high, measure this waiting time
  duration = pulseIn(EchoPin , HIGH);
// calculate the distance according to the time
  distance = (duration/2) / 28.5 ;
  Serial.print("Distance: ");
  Serial.print(distance); // Print distance value via serial
  Serial.println("cm");
  if ( distance <= 5 )
  {
    digitalWrite(PIN_LED1, HIGH);
  }
  else
  {
    digitalWrite(PIN_LED1, LOW);
  }
  if ( distance <= 10 )
  {
    digitalWrite(PIN_LED2, HIGH);
  }
  else
  {
    digitalWrite(PIN_LED2, LOW);
  }
  if ( distance <= 15 )
  {
    digitalWrite(PIN_LED3, HIGH);
  }
  else
  {
    digitalWrite(PIN_LED3, LOW);
  }
  if ( distance <= 20 )
  {
    digitalWrite(PIN_LED4, HIGH);
  }
  else
  {
    digitalWrite(PIN_LED4, LOW);
  }
}     
//**********************************************************************************
7. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, open the serial monitor and set the baud rate to 115200. You will see: the serial monitor window prints the distance value between the ultrasonic sensor and the object. Additionally, when you move your hand in front of the ultrasonic sensor, the corresponding LED lights up.

图片不存在

Project 29 Temperature Meter

1. Project Introduction:

A thermistor is a resistor whose resistance depends on temperature and changes with temperature. It is widely used in gardening, home alarm systems, and other devices. Therefore, we can use this property to make a temperature meter.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 OLED Display*1 Thermistor*1
图片不存在 图片不存在 图片不存在 图片不存在
10KΩ Resistor*1 Dupont Wires (several) USB Cable*1 Jumper Wires (several)

3. Component Knowledge:

Thermistor: A thermistor is a temperature-sensitive resistor. When the thermistor senses a change in temperature, its resistance changes. We can use this property to detect temperature intensity. The thermistor and its electronic symbol are shown below.

图片不存在

The relationship between the thermistor's resistance and temperature is:

图片不存在

Where:

Rt is the resistance of the thermistor at temperature T2;

R is the nominal resistance of the thermistor at temperature T1;

EXP[n] is e to the power of n;

B is the temperature coefficient;

T1, T2 are Kelvin temperatures (absolute temperature), Kelvin temperature = 273.15 + Celsius temperature. For the thermistor's parameters, we use: B=3950, R=10KΩ, T1=25°C. The thermistor's circuit connection method is similar to that of a photoresistor, as shown below:

图片不存在

We can use the value measured by the ADC converter to obtain the thermistor's resistance, then use the formula to obtain the temperature. Therefore, the temperature formula can be derived as:

图片不存在

4. Reading the Thermistor's Values:

First, we learn how to read the thermistor's current ADC value, voltage value, and temperature value and print them. Please wire according to the diagram below:

图片不存在

//**********************************************************************************
/*  
 * File name : Thermistor
 * Description: Read the thermistor's resistance.
 */
#define PIN_ANALOG_IN   36
void setup() {
  Serial.begin(115200);
}

void loop() {
  int adcValue = analogRead(PIN_ANALOG_IN);                       // Read ADC pin
  double voltage = (float)adcValue / 4095.0 * 3.3;                // Calculate voltage
  double Rt = 10 * voltage / (3.3 - voltage);                     // Calculate thermistor resistance
  double tempK = 1 / (1 / (273.15 + 25) + log(Rt / 10) / 3950.0); // Calculate temperature (Kelvin)
  double tempC = tempK - 273.15;                                  // Calculate temperature (Celsius)
  Serial.printf("ADC value : %d,\tVoltage : %.2fV, \tTemperature : %.2fC\n", adcValue, voltage, tempC);
  delay(1000);
}
//**********************************************************************************
Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, open the serial monitor and set the baud rate to 115200. You will see: the serial monitor window continuously displays the thermistor's current ADC value, voltage value, and temperature value. Try pinching the thermistor between your index finger and thumb (do not touch the wires) for a short period—you should see the temperature value increase.

图片不存在

5. Temperature Meter Wiring Diagram:

图片不存在

6. Adding the LCD_128×32 Library:

This project code uses a library called "LCD_128×32". If you have already added the "LCD_128×32" library, skip this step. If you have not added it, please install it before starting. The steps to add a third-party library are as follows:

Open the Arduino IDE, click "Sketch" → "Include Library" → "Add .ZIP Library...". In the pop-up window, find the file named ..\library-files\arduino-c-windows\LCD_128X32.ZIP in that directory, select the LCD_128X32.ZIP file first, then click "Open".

图片不存在

图片不存在

7. Project Code:

//**********************************************************************************
/*  
 * File name  : Temperature Meter
 * Description: LCD displays thermistor temperature.
 */
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define PIN_ANALOG_IN   36
Adafruit_SSD1306 display(128, 32, &Wire, -1);

void setup() {
  Serial.begin(115200);

  // Initialize I2C, pins are SDA=21, SCL=22
  Wire.begin(21, 22);

  // Initialize OLED display
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { 
    Serial.println(F("SSD1306 allocation failed"));
  }

  Serial.println("OLED initialized successfully");

  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE); // Set text color to white
  display.setTextSize(1);  // Set font size
  display.setCursor(0, 0); // Set cursor position (x, y)

  Serial.println("Program startup complete");
}

void loop() {
  int adcValue = analogRead(PIN_ANALOG_IN);                       // Read ADC pin
  double voltage = (float)adcValue / 4095.0 * 3.3;                // Calculate voltage
  double Rt = 10 * voltage / (3.3 - voltage);                     // Calculate thermistor resistance
  double tempK = 1 / (1 / (273.15 + 25) + (log(Rt / 10) / 3950.0)); // Calculate temperature (Kelvin)
  double tempC = tempK - 273.15;                                  // Calculate temperature (Celsius)

  display.clearDisplay();
  display.setCursor(0,0);  display.print("Voltage:"); 
  display.setCursor(50,0); display.print(voltage);
  display.setCursor(75,0); display.print("V");

  display.setCursor(0,25); display.print("tempC:");
  display.setCursor(50,25); display.print(tempC);
  display.display();
  delay(1000);
}
//**********************************************************************************
8. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: the LCD 128X32 DOT screen displays the thermistor's voltage value and the current ambient temperature.

图片不存在

Project 30 Password Lock

1. Project Introduction:

Common pushbutton sensors use one I/O port per button. When many buttons are needed, too many I/O ports are consumed. To save I/O ports, multiple buttons are arranged in a matrix. Through row/column line control, fewer I/O ports can control multiple buttons. In this project, we will learn about ESP32 and a 4x4 membrane matrix keyboard to control a servo and a buzzer.

2. Project Components:

图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Servo*1
图片不存在 图片不存在 图片不存在
4×4 Membrane Matrix Keyboard*1 USB Cable*1 Jumper Wires (several)
图片不存在 图片不存在 图片不存在
NPN Transistor (S8050)*1 Active Buzzer*1 1KΩ Resistor*1

3. Component Knowledge:

4×4 Matrix Keyboard: A keyboard is a device that integrates many keys. As shown in the figure below, a 4x4 keyboard integrates 16 keys.

图片不存在

Like LED matrix integration, in a 4x4 keyboard, each row of keys is connected by one pin, and so is each column. This connection reduces the number of processor ports used. The internal circuit is shown below.

图片不存在

The usage method is similar to that of a matrix LED—using row scanning or column scanning to detect the state of keys on each column or row. Taking the column scanning method as an example: send a low level to the 4th column (Pin4) and detect the level states of rows 1, 2, 3, and 4 to determine if buttons A, B, C, D are pressed. Then sequentially send low levels to columns 3, 2, and 1 to detect whether other buttons are pressed. This way, you can obtain the state of all keys.

4. Reading 4×4 Matrix Keyboard Key Values:

We first use a simple code to read the 4×4 matrix keyboard's key values and print them. The wiring diagram is shown below:

图片不存在

How to Install the Keypad Library:

Search for and install the third-party library in Library Manager: Keypad. If interested, you can also implement all the code yourself based on the keypad's principles.

图片不存在

//**********************************************************************************
/*  
 * File name  : 4x4 Matrix Keyboard Display
 * Description: Get matrix keyboard values
 */
#include <Keypad.h>

// Define the symbols on the keyboard buttons
char keys[4][4] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

byte rowPins[4] = {22, 21, 19, 18}; // Connect to the row pins of the keyboard
byte colPins[4] = {17, 16, 4, 0};   // Connect to the column pins of the keyboard

// Initialize an instance of the Keypad class
Keypad myKeypad = Keypad(makeKeymap(keys), rowPins, colPins, 4, 4);

void setup() {
  Serial.begin(115200); // Initialize serial, set baud rate to 115200
  Serial.println("ESP32 is ready!");  // Print the string "ESP32 is ready!"
}

void loop() {
  // Get character input
  char keyPressed = myKeypad.getKey();
  // If there is character input, send it to serial
  if (keyPressed) {
    Serial.println(keyPressed);
  }
}
//**********************************************************************************
Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, open the serial monitor and set the baud rate to 115200. You will see: when you press a key on the keyboard, the serial monitor window prints the corresponding key value, as shown below.

图片不存在

5. Password Lock Wiring Diagram:

In the previous experiment, we have learned the key values of the 4×4 matrix keyboard. Next, we use the 4×4 matrix keyboard to control the servo and buzzer.

图片不存在

6. Adding the Keypad and ESP32Servo Libraries:

You have already added the Keypad and ESP32Servo libraries previously, so there is no need to add them again. If not added, you need to add the Keypad and ESP32Servo libraries. The steps to add third-party libraries are as follows:

First, add the ESP32Servo library:

Install the third-party servo library via Library Manager: ESP32Servo. Skip if already installed.

图片不存在

7. Project Code:

//**********************************************************************************
/*  
 * File name : Password Lock
 * Description: Make a simple password lock.
 */
#include <Keypad.h>
#include <ESP32Servo.h>

// Define the symbols on the keyboard buttons
char keys[4][4] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

byte rowPins[4] = {22, 21, 19, 18};   // Connect to the row pins of the keyboard
byte colPins[4] = {17, 16, 4, 0};   // Connect to the column pins of the keyboard

// Initialize an instance of the Keypad class
Keypad myKeypad = Keypad(makeKeymap(keys), rowPins, colPins, 4, 4);

Servo  myservo;     // Create a servo object to control the servo
int servoPin = 15;  // Define the servo pin
int buzzerPin = 2; // Define the buzzer pin

char passWord[] = {"1234"}; // Store the correct password

void setup() {
  myservo.setPeriodHertz(50);           // Standard 50 Hz servo
  myservo.attach(servoPin, 500, 2500);  // Attach the servo on servoPin to the servo object
                                        // Set the servo's high-level time range for precise 0 to 180° rotation
  myservo.write(0);                     // Set the servo's initial angle
  pinMode(buzzerPin, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  static char keyIn[4];     // Store input characters
  static byte keyInNum = 0; // Store the number of input characters
  char keyPressed = myKeypad.getKey();  // Get character input
  // Process input characters
  if (keyPressed) {
    // Emit a beep each time a key is pressed
    digitalWrite(buzzerPin, HIGH);
    delay(100);
    digitalWrite(buzzerPin, LOW);
    // Store input characters
    keyIn[keyInNum++] = keyPressed;
    // Check correctness after input
    if (keyInNum == 4) {
      bool isRight = true;            // Store whether the password is correct
      for (int i = 0; i < 4; i++) {   // Check each character of the password
        if (keyIn[i] != passWord[i])
          isRight = false;            // Mark incorrect if there's a wrong character.
      }
      if (isRight) {                  // If the entered password is correct
        myservo.write(90);           // Open the switch
        delay(2000);                  // Delay for a period
        myservo.write(0);            // Close the switch
        Serial.println("passWord right!");
      }
      else {                          // Incorrect password
        digitalWrite(buzzerPin, HIGH);// Password error alarm sound
        delay(1000);
        digitalWrite(buzzerPin, LOW);
        Serial.println("passWord error!");
      }
      keyInNum = 0; // Reset input character count to 0
    }
  }
}

//**********************************************************************************
8. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: enter a 4-character password by pressing the keyboard. If the input is correct (Correct password: 1234), the servo rotates a certain angle, then returns to its original position. If the input is incorrect, an error alarm sounds.

图片不存在

Project 31 Infrared Remote Control Sound and LED

1. Project Introduction:

Infrared remote control is a low-cost, easy-to-use wireless communication technology. IR light is very similar to visible light, except its wavelength is slightly longer. This means infrared cannot be detected by the human eye, making it perfect for wireless communication. For example, when you press a button on your TV remote control, an infrared LED repeatedly switches on and off at 38,000 times per second, transmitting information (such as volume or channel control) to the infrared receiver on the TV.

We will first explain how common infrared communication protocols work. Then we will start this project with a remote control and an infrared receiver component.

2. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Infrared Receiver*1 RGB LED*1
图片不存在 图片不存在 图片不存在 图片不存在
Active Buzzer*1 220Ω Resistor*3 10KΩ Resistor*1 Infrared Remote Control*1
图片不存在 图片不存在 图片不存在 图片不存在
NPN Transistor (S8050)*1 1kΩ Resistor*1 USB Cable*1 Jumper Wires (several)

3. Component Knowledge:

Infrared (IR) Remote Control: It is a device that can emit infrared light signals. When different buttons are pressed, the infrared transmitter at the front of the remote control emits infrared rays with different commands. Infrared remote control technology is widely used, such as in TVs and air conditioners. Therefore, in today's technologically advanced society, infrared remote control technology makes it very convenient for you to switch TV channels and adjust air conditioner temperatures.

The remote control we use is shown below:

图片不存在

This infrared remote control uses NEC encoding.

Infrared (IR) Receiver: It is a component that can receive infrared light, so it can be used to receive infrared light signals emitted by an infrared remote control. The infrared receiver demodulates the received infrared light signal and converts it back to binary, then passes the information to the microcontroller.

Infrared signal modulation process diagram:

图片不存在

4. Decoding Infrared Signals:

We connect the infrared receiver component to the ESP32 according to the wiring diagram below.

图片不存在

How to Install the IRremoteESP8266 Library:

This project code uses a library called "IRremoteESP8266". If you have already added the "IRremoteESP8266" library, skip this step. If you have not added it, please install it before starting. The steps to add a third-party library are as follows:

Open the Arduino IDE, click "Sketch" → "Include Library" → "Add .ZIP Library...". In the pop-up window, find the file named ..\library-files\arduino-c-windows\IRremoteESP8266-2.7.4.ZIP in that directory, select the IRremoteESP8266-2.7.4.ZIP file first, then click "Open".

图片不存在

图片不存在

//**********************************************************************************
/*  
 * File name  : Decoded Infrared Signal
 * Description: Decode infrared remote control and print via serial.
 */
#include <Arduino.h>
#include <IRremoteESP8266.h>
#include <IRrecv.h>
#include <IRutils.h>

const uint16_t recvPin = 0; // Infrared receiver pin
IRrecv irrecv(recvPin);      // Create a class object for the receiver
decode_results results;       // Create a decode_results class object

void setup() {
  Serial.begin(115200);       // Initialize serial, set baud rate to 115200
  irrecv.enableIRIn();        // Start the receiver
  Serial.print("IRrecvDemo is now running and waiting for IR message on Pin ");
  Serial.println(recvPin);   // Print the signal received on the infrared receiver pin
}

void loop() {
  if (irrecv.decode(&results)) {          // Wait for decode
    serialPrintUint64(results.value, HEX);// Print the decode result
    Serial.println("");
    irrecv.resume();                      // Release IRremote. Receive the next value
  }
  delay(1000);
}
//**********************************************************************************
Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, open the serial monitor and set the baud rate to 115200. You will see: point the infrared remote control transmitter at the infrared receiver, press a button on the remote control, and the serial monitor will print the currently received key code value. Press the same button multiple times to ensure you have the correct code value for that button. If you see FFFFFFFF, please ignore it.

图片不存在

Write down the key code values associated with each button on the infrared remote control, as you will need this information later.

图片不存在

5. Infrared Remote Control Wiring Diagram:

图片不存在

6. Project Code:

You have already added the IRremoteESP8266 library previously, so there is no need to add it again. If not added, you need to add the IRremoteESP8266 library. The method is as shown above in this project. After adding the IRremoteESP8266 library, you can open the code we provided:

//**********************************************************************************
/*  
 * File name  : Infrared Controlled Sound and LED
 * Description: Infrared remote control controls RGB and active buzzer.
 */
#include <Arduino.h>
#include <IRremoteESP8266.h>
#include <IRrecv.h>
#include <IRutils.h>

const uint16_t recvPin = 0; // Infrared receiver pin
IRrecv irrecv(recvPin);      // Create a class object for the receiver
decode_results results;       // Create a decode_results class object

int ledPins[] = {22, 21, 4};    // Define red, green, blue pins
const byte chns[] = {0, 1, 2};        // Define PWM channels
int buzzerPin = 15;  // Buzzer pin

void setup() {
  irrecv.enableIRIn();                  // Start the receiver
  pinMode(buzzerPin, OUTPUT);
  for (int i = 0; i < 3; i++) {   // Set up PWM channels, 1KHz, 8-bit
    ledcSetup(chns[i], 1000, 8);
    ledcAttachPin(ledPins[i], chns[i]);
  }
}

void loop() {
  if(irrecv.decode(&results)) {        // Wait for decode
    handleControl(results.value);       // Process commands from the remote control
    irrecv.resume();                    // Receive the next value
  }
}

void handleControl(unsigned long value) {
  // Emit a sound when a command is received
  digitalWrite(buzzerPin, HIGH);
  delay(100);
  digitalWrite(buzzerPin, LOW);
  // Process commands
  if (value == 0xFF6897) // Received number "1"
  { 
      ledcWrite(chns[0], 255); // Common cathode LED, high level turns on the LED.
      ledcWrite(chns[1], 0);
      ledcWrite(chns[2], 0);
      delay(1000);
  }
   else if (value == 0xFF9867) // Received number '2'
   { 
      ledcWrite(chns[0], 0); 
      ledcWrite(chns[1], 255);
      ledcWrite(chns[2], 0);
      delay(1000);
   }
    else if (value == 0xFFB04F) // Received number '3'
    { 
      ledcWrite(chns[0], 0);
      ledcWrite(chns[1], 0);
      ledcWrite(chns[2], 255);
      delay(1000);
    }
    else if (value == 0xFF30CF) // Received number '4'
    {  
      ledcWrite(chns[0], 255);
      ledcWrite(chns[1], 255);
      ledcWrite(chns[2], 0);
      delay(1000);
    }
    else if (value == 0xFF18E7) // Received number '5'
    {  
      ledcWrite(chns[0], 255);
      ledcWrite(chns[1], 0);
      ledcWrite(chns[2], 255);
      delay(1000);
    }
    else if (value == 0xFF7A85)  // Received number '6'
    {  
      ledcWrite(chns[0], 0);
      ledcWrite(chns[1], 255);
      ledcWrite(chns[2], 255);
      delay(1000);
    }
    else if (value == 0xFF10EF)  // Received number '7'
    {   
      ledcWrite(chns[0], 255);
      ledcWrite(chns[1], 255);
      ledcWrite(chns[2], 255);
      delay(1000);
    }
    else{
      ledcWrite(chns[0], 0);
      ledcWrite(chns[1], 0);
      ledcWrite(chns[2], 0);
      delay(1000);
      }
  }
//**********************************************************************************
8. Project Phenomenon:

Compile and upload the code to the ESP32. After the code is uploaded successfully and powered via the USB cable, you will see: pressing buttons 1~7 on the infrared remote control causes the buzzer to beep once, while the RGB lights up red, green, blue, yellow, magenta, cyan, and white respectively. Pressing any other button (except 1-7) turns off the RGB LED.

图片不存在

Project 32 Bluetooth

This chapter mainly introduces how to perform simple data transmission between the ESP32 and a phone via Bluetooth. Project 32.1 is classic Bluetooth, and Project 32.2 is Bluetooth-controlled LED.

Project 32.1 Classic Bluetooth

1. Project Components:

图片不存在 图片不存在 图片不存在
ESP32*1 USB Cable*1 Smartphone/Tablet (self-provided)*1

In this project, we need to use a Bluetooth app called Serial Bluetooth Terminal to assist with the experiment. If you have not installed it yet, please click to install: https://www.appsapk.com/serial-bluetooth-terminal/.

Below is its icon.

图片不存在

2. Component Knowledge:

Bluetooth is a short-range communication system, divided into two types: Bluetooth Low Energy (BLE) and Classic Bluetooth. There are two modes of simple data transmission: Master mode and Slave mode.

Master Mode: In this mode, the work is performed on the master device, which can connect to slave devices. We can search for and select nearby slave devices to connect. When a device initiates a connection request in master mode, it needs the address and pairing password of the other Bluetooth device. After pairing is complete, it can connect directly.

Slave Mode: A Bluetooth module in slave mode can only accept connection requests from a master device, but cannot initiate connection requests. After connecting to the master device, it can send data to the master device and receive data from the master device. Data can be exchanged between Bluetooth devices—one device is in master mode and the other is in slave mode. When they perform data exchange, the Bluetooth device in master mode searches for and selects a nearby device to connect. During the connection establishment, they can exchange data. When the phone exchanges data with the ESP32, the phone is usually in master mode and the ESP32 is in slave mode.

图片不存在

3. Project Wiring:

Use a USB cable to connect the ESP32 board to the computer's USB port.

图片不存在

4. Project Code:

图片不存在

//**********************************************************************************
/*
 * File name : Classic Bluetooth
 * Description: ESP32 communicates with a phone via Bluetooth and prints phone data via serial
 */
#include "BluetoothSerial.h"

BluetoothSerial SerialBT;
String buffer;
void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32test"); // Bluetooth device name
  Serial.println("\nThe device started, now you can pair it with bluetooth!");
}

void loop() {
  if (Serial.available()) {
    SerialBT.write(Serial.read());
  }
  if (SerialBT.available()) {
    Serial.write(SerialBT.read());
  }
  delay(20);
}
//**********************************************************************************

5. Project Phenomenon:

Compile and upload the code to the ESP32. After uploading successfully, open the serial monitor and set the baud rate to 115200. When you see the serial printout as shown below, it means the ESP32's Bluetooth is ready and waiting to connect with the phone. (If you open the serial monitor and set the baud rate to 115200 but the following message doesn't appear, you can press the ESP32's reset button 图片不存在)

图片不存在

Please make sure your phone's Bluetooth is turned on and the "Serial Bluetooth Terminal" app is installed.

图片不存在

图片不存在

Your phone automatically searches for nearby Bluetooth devices. Click "ESP32 test" to pair. A pairing dialog appears; click "Pair". The "ESP32 test" device is now connected.

图片不存在

图片不存在

图片不存在

Open the app, click on the left side of the terminal. Select "Devices".

图片不存在

图片不存在

Select ESP32test under Classic Bluetooth mode, and a successful connection message will appear as shown below.

图片不存在

图片不存在

Now, data can be transmitted between your phone and computer via the ESP32.

Enter "Hi!" in the text box in the IDE. When the phone receives it, reply "Hi!" from your phone. The phone sends "Hello!"; when the computer receives it, reply "Hello!" to your computer.

图片不存在

图片不存在

Project 32.2 Bluetooth Controlled LED

1. Project Components:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 Red LED*1 Smartphone/Tablet (self-provided)*1
图片不存在 图片不存在 图片不存在
220Ω Resistor*1 Jumper Wires*2 USB Cable*1

2. Project Wiring:

图片不存在

3. Project Code:

图片不存在

//**********************************************************************************
/*
 * File name  : Bluetooth Controlled LED
 * Description: Phone controls ESP32 indicator light via Bluetooth.
 *             When the phone sends "LED_on", the ESP32's LED lights up.
 *             When the phone sends "LED_off", the ESP32's LED turns off.
 */
#include "BluetoothSerial.h"
#include "string.h"
#define LED 15
BluetoothSerial SerialBT;
char buffer[20];
static int count = 0;
void setup() {
  pinMode(LED, OUTPUT);
  SerialBT.begin("ESP32test"); // Bluetooth device name
  Serial.begin(115200);
  Serial.println("\nThe device started, now you can pair it with bluetooth!");
}

void loop() {
  while(SerialBT.available())
  {
    buffer[count] = SerialBT.read();
    count++;
  }
  if(count>0){
    Serial.print(buffer);
    if(strncmp(buffer,"led_on",6)==0){
      digitalWrite(LED,HIGH);
    }
    if(strncmp(buffer,"led_off",7)==0){
      digitalWrite(LED,LOW);
    }
    count=0;
    memset(buffer,0,20);
  }
}
//**********************************************************************************

4. Project Phenomenon:

Compile and upload the code to the ESP32. The APP operation is the same as Project 32.1. To control the external LED, just change the sent content to "led_on" and "led_off". Data sent from the mobile app:

图片不存在

图片不存在

LED phenomenon:

图片不存在

Note: If the sent content is not "led_on" or "led_off", the LED state will not change. If the LED is on, it stays on when receiving irrelevant content; correspondingly, if the LED is off, it stays off when receiving irrelevant content.

Project 33 WiFi Operating Modes

In today's rapidly developing technological era, the method of centrally controlling smart devices via a smartphone has gradually gained popularity. This method uses a microcontroller to establish a connection between the phone and smart devices via a WiFi module and the Internet, enabling remote control of smart devices. Our development board has a built-in WiFi module. In this chapter, we will focus on ESP32 WiFi development.

The ESP32 has 3 different WiFi operating modes: Station mode, AP mode, and AP+Station mode.

Project 33.1: WiFi Station Mode

1. Experimental Components:

图片不存在 图片不存在
USB Cable x1 ESP32x1

2. Experimental Wiring:

Use a USB cable to connect the ESP32 board to the computer's USB port.

图片不存在

3. Component Knowledge:

Station Mode: When the ESP32 selects Station mode, it acts as a WiFi client. It can connect to a router network and communicate with other devices on the router via the WiFi connection. As shown in the figure below, the PC and router are already connected. If the ESP32 wants to communicate with the PC, the PC needs to be connected to the router.

图片不存在

4. Project Code:

//**********************************************************************************
/*
 * File name  : WiFi Station Mode
 * Mode : Use ESP32 to connect to a router
 */
#include <WiFi.h> // Include the ESP32 WiFi library header file.

// Enter the correct router name and password.
const char *ssid_Router     = "ChinaNet-2.4G-0DF0"; // Enter router name
const char *password_Router = "ChinaNet@233"; // Enter router password

void setup(){
  Serial.begin(115200);
  delay(2000);
  Serial.println("Setup start");
  WiFi.begin(ssid_Router, password_Router);// Set ESP32 to "Station Mode" and connect to the router.
  Serial.println(String("Connecting to ")+ssid_Router);
// Check every 0.5s if ESP32 is connected to the router successfully.  
  while (WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected, IP address: ");
  Serial.println(WiFi.localIP());// Print the IP address assigned to ESP32 in the serial monitor.
  Serial.println("Setup End");
}

void loop() {
}
//**********************************************************************************
Since WiFi names and passwords vary by location, users need to enter the correct WiFi name and password in the box shown below before running the program code.

图片不存在

5. Project Phenomenon:

After confirming the correct WiFi name and password, compile and upload the code to the ESP32 board. After uploading successfully, open the serial monitor and set the baud rate to 115200. When the ESP32 successfully connects to ssid_Router, the serial monitor will print the IP address assigned to the ESP32 by the WiFi. The serial monitor window will then display as follows: (If you open the serial monitor and set the baud rate to 115200 but the following message doesn't appear, you can press the ESP32's reset button 图片不存在)

图片不存在

Project 33.2: WiFi AP Mode

1. Experimental Components & Wiring:

The experimental components and wiring are the same as Project 33.1: WiFi Station Mode above.

2. Component Knowledge:

AP Mode: When the ESP32 selects AP mode, it creates a hotspot network independent of the Internet, waiting for other WiFi devices to connect. As shown in the figure below, the ESP32 acts as a hotspot. If a phone or PC needs to communicate with the ESP32, it must connect to the ESP32's hotspot. Communication is only possible after a connection is established through the ESP32.

图片不存在

3. Project Code:

//**********************************************************************************
/*
 * File name  : WiFi AP
 * Description: Set ESP32 to open an access point
 */
#include <WiFi.h> // Include the ESP32 WiFi library header file.

const char *ssid_AP     = "ESP32_Wifi"; // Enter AP name
const char *password_AP = "12345678"; // Enter AP password

IPAddress local_IP(192,168,1,108);// Set ESP32's own IP address
IPAddress gateway(192,168,1,1);   // Set ESP32's own gateway
IPAddress subnet(255,255,255,0);  // Set ESP32's own subnet mask

void setup(){
  Serial.begin(115200);
  delay(2000);
  Serial.println("Setting soft-AP configuration ... ");
  WiFi.disconnect();
  WiFi.mode(WIFI_AP);
  Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");
  Serial.println("Setting soft-AP ... ");
  boolean result = WiFi.softAP(ssid_AP, password_AP);
  if(result){
    Serial.println("Ready");
    Serial.println(String("Soft-AP IP address = ") + WiFi.softAPIP().toString());
    Serial.println(String("MAC address = ") + WiFi.softAPmacAddress().c_str());
  }else{
    Serial.println("Failed!");
  }
  Serial.println("Setup End");
}

void loop() {
}
//**********************************************************************************
Before running the code, you can change the ESP32's AP name and password as shown in the figure below. Of course, you can leave them unchanged by default.

图片不存在

4. Project Phenomenon:

Enter the ESP32's AP name and password correctly. Compile and upload the code to the ESP32 board. After uploading successfully, open the serial monitor and set the baud rate to 115200. The serial monitor window will then display as follows: (If you open the serial monitor and set the baud rate to 115200 but the following message doesn't appear, you can press the ESP32's reset button 图片不存在)

图片不存在

While observing the serial monitor output, turn on your phone's WiFi scanning feature. You can see the ESP32's ssid_AP being broadcast—in this program code it's called "ESP32_Wifi". You can enter the password "12345678" to connect to it, or you can modify the AP name and password by changing the program code.

图片不存在

Project 33.3: WiFi AP+Station Mode

1. Experimental Components & Wiring:

The experimental components and wiring are the same as Project 33.1: WiFi Station Mode and Project 33.2: WiFi AP Mode above.

2. Component Knowledge:

AP+Station Mode: In addition to AP mode and Station mode, the ESP32 can also use AP mode and Station mode simultaneously. This mode includes the functions of the previous two modes. Enable the ESP32's Station mode and connect it to the router network—it can communicate with the Internet through the router. Simultaneously enable 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 the ESP32.

3. Project Code:

//**********************************************************************************
/*
 * File name : WiFi AP+Station
 * Description: ESP32 connects to the user's router and opens an access point
 */
#include <WiFi.h>

const char *ssid_Router     =  "ChinaNet-2.4G-0DF0";  // Enter router name
const char *password_Router =  "ChinaNet@233";  // Enter router password
const char *ssid_AP         =  "ESP32_Wifi"; // Enter AP name
const char *password_AP     =  "12345678";  // Enter AP password

void setup(){
  Serial.begin(115200);
  Serial.println("Setting soft-AP configuration ... ");
  WiFi.disconnect();
  WiFi.mode(WIFI_AP);
  Serial.println("Setting soft-AP ... ");
  boolean result = WiFi.softAP(ssid_AP, password_AP);
  if(result){
    Serial.println("Ready");
    Serial.println(String("Soft-AP IP address = ") + WiFi.softAPIP().toString());
    Serial.println(String("MAC address = ") + WiFi.softAPmacAddress().c_str());
  }else{
    Serial.println("Failed!");
  }

  Serial.println("\nSetting Station configuration ... ");
  WiFi.begin(ssid_Router, password_Router);
  Serial.println(String("Connecting to ")+ ssid_Router);
  while (WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected, IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Setup End");
}

void loop() {
}
//**********************************************************************************
It is similar to Project 33.1 and Project 33.2 above. Before running the code, you need to modify ssid_Router, password_Router, ssid_AP, and password_AP as shown in the red boxes below.

图片不存在

4. Project Phenomenon:

After confirming the code modifications are correct, compile and upload the code to the ESP32 board. After uploading successfully, open the serial monitor and set the baud rate to 115200. The serial monitor window will then display as follows: (If you open the serial monitor and set the baud rate to 115200 but the following message doesn't appear, you can press the ESP32's reset button 图片不存在)

图片不存在

Open your phone's WiFi search feature and you can see the ESP32's ssid_AP being broadcast.

图片不存在

Project 34 WiFi Test

1. Experimental Introduction:

In this experiment, we first use the ESP32's WiFi Station mode to read the WiFi IP address, then connect to the WiFi via an app to read the characters sent by the function buttons on the app.

2. Experimental Components:

图片不存在 图片不存在 图片不存在
ESP32*1 USB Cable*1 Smartphone/Tablet(self-provided)*1

3. Experimental Wiring:

Use a USB cable to connect the ESP32 board to the computer's USB port.

图片不存在

4. Modify the Code

You need to first change the user WiFi name and password in the code 图片不存在 to your own WiFi name and password.

5. Upload the Code

Upload the code and open the serial monitor (baud rate 115200) -> press the EN button on the board to restart -> view the device IP.

After the ESP32 uploads the code, it automatically connects to the WiFi defined in the code.

图片不存在

6. Open the Browser:

Enter the IP address from the serial log in a computer or phone browser, and the following interface will appear.

Img

This is a web service provided by the ESP32.

Special Note: Ensure the computer network, phone/tablet network, ESP32 board, router, and the WiFi name and password entered in the code must all be on the same local area network (WiFi).

6. Experimental Phenomenon

Click the various function buttons on the browser, and the serial monitor will print the corresponding characters received.

图片不存在

Note: If you open the serial monitor and set the baud rate to 115200 but the following message doesn't appear, you can press the ESP32's reset button 图片不存在

Project 35 WiFi Smart Home

1. Experimental Description:

In the previous experiments, we have learned about the ESP32's three WiFi modes: Station mode, AP mode, and AP+Station mode. In this chapter, we will use the ESP32's WiFi Station mode to connect to WiFi via an app to control multiple sensors/modules, achieving a WiFi smart home effect.

2. Experimental Equipment:

图片不存在 图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 DC Motor*1 Relay Module*1
图片不存在 图片不存在 图片不存在 图片不存在
Servo*1 Temperature and Humidity Sensor*1 Ultrasonic Sensor*1 Dupont Wires (several)
图片不存在 图片不存在 图片不存在 图片不存在
Smartphone/Tablet(self-provided)*1 Breadboard Power Supply Module*1 6-cell AA Battery Holder*1 Fan Blades*1
图片不存在 图片不存在 图片不存在
AA Batteries(self-provided)*6 MicroUSB Cable*1 Jumper Wires (several)

3. Experimental Wiring Diagram:

Relay ESP32 Board Temperature and Humidity Sensor ESP32 Board
Gnd Gnd - G
Vcc 3.3V + 5V
IN IO32 out IO15
Ultrasonic Sensor ESP32 Board 130 Fan Module ESP32 Board
Vcc 5V G G
Trig IO14 V 5V
Echo IO27 INA IO18
Gnd GND INB IO19
Servo ESP32 Board
Red Wire 5V
Brown Wire G
Orange Wire IO4

图片不存在

4. Adding the xht11 and ESP32Servo Libraries:

This project code uses libraries called "dht11" and "ESP32Servo". If you have not added them yet, please add them before starting.

These two open-source libraries are provided by third parties to facilitate reading data from the temperature and humidity module and controlling the servo. If you were to implement everything yourself, you would need to write a lot of code, and it might not be as efficient as others.

Therefore, when actually working on projects, we focus more on the business logic rather than unnecessarily reinventing the wheel.

Adding DHT11 and ESP32Servo Libraries Respectively:

图片不存在

图片不存在

5. Project Code:

See the example source code in the compressed package.

Special Note: You need to first change the user WiFi name and password in the experimental code 图片不存在 to your own WiFi name and password.

6. Experimental Phenomenon:

Special Note: Ensure the computer network, phone/tablet network, ESP32 board, router, and the WiFi name and password entered in the code must all be on the same local area network (WiFi).

After confirming the WiFi name and password in the code are correctly modified, compile and upload the code to the ESP32 board.

Open the serial monitor and set the baud rate to 115200. The serial monitor will print the detected WiFi IP address. (Note: If you open the serial monitor and set the baud rate to 115200 but the following message doesn't appear, you can press the ESP32's reset button 图片不存在)

图片不存在

Open a browser on your phone or computer, enter the device IP address from the serial monitor, and the control panel will open.

Img

For details, refer to the video tutorial "WiFi Smart Home"

Project 36 MQTT IoT

1. Experimental Description:

In the previous experiments, we have mastered the basics of WiFi and built a prototype of a smart home project within a local area network.

This lesson will focus on IoT-related knowledge, further improving the smart home project based on this, ultimately achieving a cross-network remote anti-theft alarm system.

2. IoT Knowledge:

IoT technology is currently widely used in industry, healthcare, and daily life. It is mainly reflected in the ability of terminals such as phones and computers to obtain and control various devices in real time.

In addition to the main board and various sensors we encountered in the course, there is also a communication technology involved: MQTT. This lesson will use MQTT communication technology to achieve real-time interaction between a phone and a PIR sensor.

The core of IoT is to enable communication between phones, computers, and hardware devices.

In this tutorial, we can understand the entire process as a "message delivery chain":

Phone App -> MQTT Server -> ESP32 Board -> LED Light / Relay / Sensor

Img

The MQTT server is a free test server provided by Qiguopai, deployed on the Internet. Both the app and the ESP32 board connect to this server via WiFi.

You can think of it as a "message relay station":

  • App and Esp32 agree on an identifier;

  • App sends the identifier + message to the MQTT server;

  • The server then forwards the message to the Esp32 board with that identifier;

2. Experimental Equipment:

图片不存在 图片不存在 图片不存在
ESP32*1 Breadboard*1 PIR Sensor*1
图片不存在 图片不存在
LED Bulb*1 220 ohm or 1K Resistor
图片不存在 图片不存在 图片不存在
Smartphone/Tablet(self-provided)*1 Dupont Wires (several) Jumper Wires (several)

3. Experimental Wiring Diagram:

PIR Sensor ESP32 Board
+ 3.3V
- GND
OUT IO35
LED Bulb ESP32 Board
Cathode GND
Anode IO23

3. Experimental Code:

Open the code from the project package, then install the IoT protocol library PubSubClient. Code analysis can be found in the video explanation.

If you want to learn app development, you can download the following source code. If you are learning microcontroller development, you just need to download and install the package.

图片不存在

4. Experimental Phenomenon:

When someone enters the PIR sensor's detection range, the LED lights up and sends data to the phone APP.

For a complete demonstration, refer to the video tutorial.

图片不存在

图片不存在

5. Extended Thinking:

  • Can more sensors be connected? For example, a gas sensor can detect whether there is a gas leak in the kitchen in real time;

  • Connect an external 6V power adapter to solve long-term power supply issues;

  • 3D print a storage enclosure for a nicer appearance, more like a commercialized product.