Skip to content

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 project for the 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 (path): ..\program-code\arduino-c-windows-code.(The path for subsequent project code is the same, i.e.: same as below.)

//*************************************************************************************
/*
 * File Name : Hello World
 * Description : Input the letter R, serial display shows "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 later are the same, i.e.: same as below.)

Select the correct port (COM). (Note: The corresponding port will only be visible after connecting the ESP32 board to the computer via a USB cable.)

Note: For macOS users, if the upload 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 not successful, you can click again and press and hold the Boot button on the ESP32 board. 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 then 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.

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 pole. The short leg is the negative pole, connected to GND, and the long leg is the positive pole, connected to 3.3V or 5V.

(2) Five-Color-Band Resistor

A resistor is an electronic component in a circuit that limits or regulates the flow of current. On the left is the appearance of the resistor, and on the right is the symbol representing 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 like 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 three examples: 220Ω Resistor ×10

10KΩ Resistor ×10

1KΩ Resistor ×10

At 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 = 3 V / 10 KΩ= 0.0003A= 0.3mA.

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

(3) Breadboard

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

The appearance and internal structure of the breadboard are shown in the figure above. The common minimum unit breadboard is divided into three parts: top, middle, and bottom. The top and bottom parts are generally narrow strips consisting of one or two rows of sockets. The middle part is a strip consisting of a central isolation groove and five rows of sockets above and below.

The two narrow strips of the breadboard each have two rows of sockets, and the two rows are not connected to each other; they are generally used as power supply paths. The first row marked "+" has 10 groups of sockets (internally connected), all positive; the second row marked "-" has 10 groups of sockets (internally connected), all grounded. The first and second rows at the bottom of the breadboard have the same structure as above. 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 sockets above and below. The 5 sockets in the same column are connected to each other; columns and the parts above and below the groove are not connected. The appearance and structure are shown below:

The middle wide strip's connection holes are divided into upper and lower parts and are the main working area of the breadboard, used for inserting components and jumper wires. The 5 sockets in the same column (i.e., a-b-c-d-e, f-g-h-i-j) are connected to each other; columns and the parts 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 upper narrow strip is used for power, and one row of the lower 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 via a USB cable.

4. Project Wiring Diagram:

First, disconnect all power to the ESP32. Then build the circuit according to the wiring diagram. After the circuit is built and verified to be correct, connect the ESP32 to the computer with a USB cable.

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

Warning: Short circuits may cause high currents in the circuit, resulting in overheating of components and permanent damage to the hardware.

Note:

How to connect the LED

How to identify the five-color-band 220Ω resistor

5. Project Code:

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

//**********************************************************************
/*
 * File Name : Light Up LED
 * Description : Turn on a light.
 */
#define LED_BUILTIN 15

// The setup function runs only once when the board is 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 later are the same, i.e.: same as below.)

Select the correct port (COM). (Note: The corresponding port will only be visible after connecting the ESP32 board to the computer via a USB cable.)

Note: For macOS users, if the upload 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 not successful, you can click again and press and hold the Boot button on the ESP32 board. 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, disconnect all power to the ESP32. Then build the circuit according to the schematic and wiring diagrams. After the circuit is built and verified to be correct, connect the ESP32 to the computer with a USB cable.

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

Warning: Short circuits may cause high currents in the circuit, resulting in overheating of components and permanent damage to the hardware.

Note:

How to connect the LED

How to identify the five-color-band 220Ω resistor

4. Project Code:

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

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

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

// The loop function runs repeatedly 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, make the voltage low
  delay(500);                       // Delay 0.5s
}
//*************************************************************************************
Before uploading the project code to the ESP32, please check the Arduino IDE configuration. (The steps for uploading project code later are the same, i.e.: same as below.)

Click "Tools" and confirm the "Board" type and "Port (COM)" as shown below: (Note: The corresponding port will only be visible 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 not successful, you can click again and press and hold the Boot button on the ESP32 board. 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 observe: the LED in the circuit blinks repeatedly.

Project 04 Breathing Light

1. Project Introduction:

In previous lessons, we learned that an LED has on/off states. How do we achieve an intermediate state? How do we output an intermediate state to make the LED "half-lit"? This is what we will learn. A breathing light is when an LED gradually brightens from off and then dims back to off, like "breathing". So how do we control the brightness of an LED? We will use the ESP32's PWM 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 continuous in both time and amplitude. 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. A familiar example of an analog signal is: the temperature throughout the day changes continuously rather than abruptly jumping from 0 to 10. However, the value of a digital signal can change instantaneously. This change is represented by the numbers 1 and 0 (the basis of binary code). As shown in the figure 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 of using digital signals to control analog circuits. Ordinary processors cannot directly output analog signals. PWM technology makes this conversion (converting a digital signal to an analog signal) very convenient. PWM technology uses digital pins to send square waves of a certain frequency, i.e., outputs of high and low levels, alternating for a period of time. The total time of each high-low level group is generally fixed and called the period (note: the reciprocal of the period is the frequency). The time the high level is 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 figure below shows the corresponding analog signal voltage changes between 0V-3.3V (high level is 3.3V) for pulse widths of 0%-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 ESP32's PWM output pins 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 the bit is 31. For example: to generate PWM with 8-bit resolution (2^8 = 256, range 0 ~ 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 on GPIO15, with the pulse width gradually increasing from 0% to 100%, and then gradually decreasing from 100% to 0%.

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

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

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

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

Click "Tools" and confirm the "Board" type and "Port (COM)" as shown below: (Note: The corresponding port will only be visible 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 not successful, you can click again and press and hold the Boot button on the ESP32 board. 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 observe: the LED in the circuit gradually brightens from dim and then dims back from bright, just like breathing.

Project 05 Traffic Light

1. Project Introduction:

Traffic lights are very common in our daily life. Traffic lights are composed of red, yellow, and green colors following a certain time pattern. 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 (some) 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 (path): ..\program-code\arduino-c-windows-code.(The path for subsequent project code is the same, i.e.: same as below.)

//**********************************************************************
/*
 * File Name  : Traffic Light
 * Description : Simulate a traffic light.
 */
#define PIN_LED_RED   0   // Define red pin
#define PIN_LED_YELLOW   2   // Define yellow pin
#define PIN_LED_GREEN  15   // Define 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);// Light up the red light
   delay(5000);// Delay 5 s
   digitalWrite(PIN_LED_RED, LOW); // Turn off the red light
   delay(500);// Delay 0.5 s
   for(int i=0;i<3;i++)// Flash 3 times.
  {
   digitalWrite(PIN_LED_YELLOW, HIGH);// Light up the yellow light
   delay(500);// Delay 0.5 s
   digitalWrite(PIN_LED_YELLOW, LOW);// Turn off the yellow light
   delay(500);// Delay 0.5 s
   }
   digitalWrite(PIN_LED_GREEN, HIGH);// Light up the green light
   delay(5000);// Delay 5 s
   digitalWrite(PIN_LED_GREEN, LOW);//
  delay(500);// Delay 0.5 s
}
//*************************************************************************************
Before uploading the project code to the ESP32, please check the Arduino IDE configuration. (The steps for uploading project code later are the same, i.e.: same as below.)

Click "Tools" and confirm the "Board" type and "Port (COM)" as shown below: (Note: The corresponding port will only be visible 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 not successful, you can click again and press and hold the Boot button on the ESP32 board. 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 observe: 1. First, the red light will be on for 5 seconds and then turn off; 2. Next, the yellow light will flash 3 times and then turn off; 3. Then, the green light will be on for 5 seconds and then turn off; 4. Repeat steps 1-3 continuously.

Project 06 RGB LED

1. Project Introduction:

An RGB LED is composed of three colors (red, green, blue), and different colors can be emitted by mixing these three basic 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 an RGB LED is very basic, it is a great way to introduce the fundamentals of electronics and coding to yourself or others.

2. Project Components:

ESP32*1 Breadboard*1 RGB LED*1
220Ω Resistor*3 Jumper Wires (some) 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 one common cathode. To change the brightness of the RGB LED, we can use the PWM pins of the ESP. The PWM pins will give the RGB LED signals with different duty cycles to obtain 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 : Display random colors using RGB.
 */
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, 8bit
    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 LED.
  ledcWrite(chns[1], 255 - g);
  ledcWrite(chns[2], 255 - b);
}
//*************************************************************************************

6. Project Phenomenon:

Compile and upload the code to the ESP32. After successful upload, power it via the USB cable. You will observe: the RGB LED begins 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 water effect.

2. Project Components:

ESP32*1 Breadboard*1 Red LED*10
220Ω Resistor*10 Jumper Wires (some) USB cable*1

3. Project Wiring Diagram:

4. Project Code:

This project is designed to create a flowing light. The steps are: 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 flowing "motion".

//**********************************************************************
/*
 * File Name : Flowing Light
 * Description : Use ten LEDs to demonstrate flowing lights
 */
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:

Compile and upload the code to the ESP32. After successful upload, power it via the USB cable. You will observe: 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 digital tube is an electronic display device that displays decimal numbers. It is widely used in digital clocks, electronic instruments, basic calculators, and other electronic devices that display numerical information. Even bombs seen in movies have seven-segment digital tubes. Although seven-segment digital tubes may not look modern, they are an alternative to more complex dot matrix displays and are easy to use in low light 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 (some) USB cable*1

3. Component Knowledge:

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

In a common cathode 7-segment digital tube, all cathodes (or negative poles) of the segmented 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, all anodes (positive poles) of the 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 part 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 burn out. In this experiment, we use a common common cathode one-digit digital tube. As we 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: The orientation of the seven-segment digital tube inserted into the breadboard should match the wiring diagram, with an extra dot at the lower right corner.

5. Project Code:

Number display has 7 segments, and decimal point display has 1 segment. When displaying certain numbers, the corresponding segments are lit. For example, when displaying the number 1, segments b and c are turned on.

//**********************************************************************
/*
 * File Name : One-digit Digital Tube
 * Description : 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 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 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 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 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 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 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 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 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 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 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 digital pin LED as output.
  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 number 9
delay(1000); // Delay 1 s
digital_8();// Display number 8
delay(1000);
digital_7();// Display number 7
delay(1000);
digital_6();// Display number 6
delay(1000);
digital_5();// Display number 5
delay(1000);
digital_4();// Display number 4
delay(1000);
digital_3();// Display number 3
delay(1000);
digital_2();// Display number 2
delay(1000);
digital_1();// Display number 1
delay(1000);
digital_0();// Display number 0
delay(1000);
}}
//**********************************************************************

6. Project Phenomenon:

Compile and upload the code to the ESP32. After successful upload, power it via the USB cable. You will observe: the one-digit digital tube displays 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 clock displays, scoreboards on sports fields, and counting people in parks. Due to its low cost 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 (some) USB cable*1

3. Component Knowledge:

Four-digit Digital Tube: Four-digit digital tubes come in common anode and common cathode types. The display principle is similar to that of a one-digit digital tube. Both use 8 GPIO ports to control the display segments, i.e., 8 LED lights. However, this one has 4 digits, so 4 more GPIO ports are needed to control the digit selection, i.e., which individual digital tube lights up. The digit switching is very fast and indistinguishable to the naked eye, so it appears that multiple digital tubes are displaying simultaneously.

Our four-digit digital tube is common cathode.

The figure below shows the pinout of the 4-digit digital tube. G1, G2, G3, G4 are the pins for controlling the digits.

The figure 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 : Four-digit tube displays numbers from 0 to 9999.
 */
#define d_a 18   // Define digital tube 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 first 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 pin
  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()
{

  // Count 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++)
        {
          // Flashing 125 times per second equals 1 second.
          // 1000/8=125
          for(int q = 0;q<125;q++)
          {
            Display(1,l);// 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, n ranges from 0 to 9
void Display(unsigned char g,unsigned char n)
{
  digitalWrite(d_a,LOW);      // Turn off 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 first digit
      digitalWrite(G2,HIGH);
      digitalWrite(G3,HIGH);
      digitalWrite(G4,HIGH);
      break;
    case 2:
      digitalWrite(G1,HIGH);
      digitalWrite(G2,LOW);   // Select second digit
      digitalWrite(G3,HIGH);
      digitalWrite(G4,HIGH);
      break;
    case 3:
      digitalWrite(G1,HIGH);
      digitalWrite(G2,HIGH);
      digitalWrite(G3,LOW);   // Select third digit
      digitalWrite(G4,HIGH);
      break;
    case 4:
      digitalWrite(G1,HIGH);
      digitalWrite(G2,HIGH);
      digitalWrite(G3,HIGH);
      digitalWrite(G4,LOW);   // Select fourth digit
      break;
    default:break;
  }

  digitalWrite(d_a,num[n][0]);      // Look up code value table for 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 successful upload, power it via the USB cable. You will observe: the four-digit digital tube counts from 0000, incrementing by 1 up to 9999, and repeats these actions in an infinite loop.

Project 10 8x8 Dot Matrix Display

1. Project Introduction:

A dot matrix display is an electronic digital display device that can show 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 8x8 Dot Matrix*1
220Ω Resistor*8 Jumper Wires (some) USB cable*1

3. Component Knowledge:

8x8 Dot Matrix: It consists of 64 LEDs. There are two types: row common anode and row common cathode. Our module is row common anode, meaning each row has a line connecting the anodes of the LEDs together, while 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's level is 1 and a column's level is 0, the corresponding LED lights up. If you want to light up the LED at the first point, you should set pin 9 to high level and pin 13 to low level. If you want to light up the first row of LEDs, you should set pin 9 to high level and pins 13, 3, 4, 10, 6, 11, 15, and 16 to low level. If you want to light up the first column of LEDs, set pin 13 to low level and pins 9, 14, 8, 12, 1, 7, 2, and 5 to high level.

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

4. Project Wiring Diagram:

5. Project Code:

//**********************************************************************************
/*
 * File Name  : 8x8 Dot Matrix Display
 * Description : 8x8 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 successful upload, power it via the USB cable. You will observe: the 8*8 dot matrix displays numbers 0~9 in sequence, repeating.

Project 11 Shift Register Controlling 8 LEDs

1. Project Introduction:

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

Usually, the number of I/O ports on a development board is limited. If you need to control a large number of devices, there may not be enough I/O ports. For example, in Project 2, each light requires one I/O port to control. If you need to control multiple lights, the I/O ports will be used up. To handle this scenario, we introduce a shift register to expand the I/O ports. In this project, we will use the ESP32, 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 (some) USB cable*1

3. Component Knowledge:

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

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

Img

Pin Descriptions:

Pin: Pin Description:
Pin 13 OE Is an output enable pin used to ensure whether the latch data is input to the Q0-Q7 pins. When low, high level output is disabled. In this experiment, we connect it directly to GND to maintain low level and output data.
Pin 14 SI/DS This is the data receiving pin of the 74HC595, i.e., the serial data input. Only one bit can be input at a time. After 8 consecutive inputs, a byte is formed.
Pin 10 SCLR/MR A pin to initialize the storage register. Initializes the internal storage register when low. In this experiment, we connect it to VCC to maintain high level.
Pin 11 SCK/SH_CP Clock pin of the shift register. On the rising edge, the data in the shift register shifts back and receives new data input.
Pin 12 RCK/ST_CP 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, 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 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 pattern.
 */
int dataPin = 14;   // Pin connected to 74HC595 DS (Pin14)
int latchPin = 12;  // 74HC595 ST_CP connected pin (Pin12)
int clockPin = 13;  // 74HC595 SH_CP connected pin (Pin11)

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

void loop() {
  // Define a single byte variable, using 8 bits to represent the state of 8 LEDs.
  // The variable is assigned 0x01, i.e., binary 00000001, indicating only one light is on.
  byte x = 0x01;    // 0b 0000 0001
  for (int j = 0; j < 8; j++) { // Let 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 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 data to parallel output port.
  digitalWrite(latchPin, HIGH);
}
//**********************************************************************************

6. Project Phenomenon:

Compile and upload the code to the ESP32. After successful upload, power it via the USB cable. You will observe: 8 LEDs start blinking in a flowing 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, alarms, electronic toys, phones, timers, etc. It has an internal vibration source. Simply connect a 5V power supply, and it will continuously produce a buzzing sound. In this project, we will use the ESP32 to control an active buzzer to produce a "beep beep" sound.

2. Project Components:

ESP32*1 Breadboard*1 Active Buzzer*1 NPN Transistor (S8050)*1
1KΩ Resistor*1 Jumper Wires (some) USB cable*1

3. Component Knowledge:

Active Buzzer: It has a simple internal oscillator circuit that converts constant DC power into a pulse signal of a specific frequency. Once the active buzzer receives a high level, it produces 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 two buzzers look very similar, but the one with a green circuit board is a passive buzzer, and the 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, the ESP32's GPIO output capability 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. It 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 flows between "b-e", "c-e" will allow several times the current to pass (transistor amplification). At this point, the transistor operates in the amplification region. When the current between "b-e" exceeds a certain value, "c-e" will no longer allow the current to increase. At this point, the transistor operates in the saturation region. There are two types of transistors as shown below: PNP and NPN.

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

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

4. Project Wiring Diagram:

Note: The buzzer power supply in this circuit is 5V. At 3.3V power, the buzzer can work but with reduced volume.

5. Project Code:

//**********************************************************************
/*
 * File Name   : Active Buzzer
 * Description : Active buzzer beeps.
 */
#define buzzerPin  15  // Define 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 successful upload, power it via the USB cable. You will observe: the active buzzer produces a "beep beep" sound.

Project 13 Passive Buzzer

1. Project Introduction:

In the previous project, we studied the active buzzer, which can only produce one sound and may seem monotonous. This project will learn about another type of buzzer, the passive buzzer. Unlike the active buzzer, the passive buzzer can produce 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 (some) 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. It looks very similar to an active buzzer, but the one with a green circuit board is a passive buzzer, and the 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 produces an alarm.
 */
#define LEDC_CHANNEL_0 0

// LEDC timer uses 13-bit resolution

#define LEDC_TIMER_13_BIT  13

// Define utility I/O port

#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 buzzer to 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 successful upload, power it via the USB cable. You will observe: 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 push button, and an LED to make a mini desk lamp.

2. Project Components:

ESP32*1 Breadboard*1 Push Button*1
10KΩ Resistor*1 Red LED*1 220Ω Resistor*1
Button Cap*1 Jumper Wires (some) USB cable*1

3. Component Knowledge:

Push Button: A push button can control the on/off state of a circuit. When the push button is connected in a circuit and not pressed, the circuit is open.

When you press the button, the circuit closes, but it opens again when released. But why does it only conduct when pressed? This has to do with the internal structure of the push button. Before pressing, current cannot pass from one end of the button to the other. When pressed, the internal metal piece connects both sides, allowing current to pass through.

The internal structure of the push button is shown: . Before pressing, 1 and 2 are connected, and 3 and 4 are also connected, but 1-3, 1-4, 2-3, and 2-4 are disconnected. Only when the button is pressed are 1-3, 1-4, 2-3, or 2-4 connected.

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

Push Button Schematic:

What is button debouncing?

The ideal switch circuit is "press the button - instantly conducts" and "press again - instantly disconnects", but in reality it is not so.

Push buttons typically use mechanical spring switches, and mechanical spring switches generate a series of bounces at the moment the mechanical contacts open and close (usually around 10ms) due to spring action. This causes the push button switch to not immediately and stably close the circuit when closed, nor to completely and instantly disconnect when opened.

How to eliminate button bouncing?

There are two common debouncing methods: software and hardware. Here we focus on the convenient 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 achieve button debouncing.

4. Project Wiring Diagram:

Note:

How to connect the LED

How to identify the five-color-band 220Ω and 10KΩ resistors

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 digital pin PIN_LED as output.
  pinMode(PIN_LED, OUTPUT);
  pinMode(PIN_BUTTON, INPUT);
}

// The loop function runs repeatedly 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 successful upload, power it via the USB cable. You will observe: press the button, the LED lights up; when the button is released, the LED remains on. Press the button again, the LED turns off; when the button is released, the LED remains 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. Fine sand is placed on one side with a very small channel in the middle. When the hourglass is placed upright with the sand side on top, the sand flows down through the channel to the other side due to gravity. When all the sand has flowed to the bottom, it is flipped over. By recording the number of times this is repeated in a day, the next day you can know the approximate time by the number of times the sand has flowed back and forth. In this lesson, we will use the ESP32 to control a tilt switch and LEDs to simulate an hourglass, creating an electronic hourglass.

2. Project Components:

ESP32*1 Breadboard*1 Tilt Switch*1 10KΩ Resistor*1
Red LED*4 220Ω Resistor*1 Jumper Wires (some) USB cable*1

3. Component Knowledge:

A tilt switch is also called a digital switch or ball switch. It has a metal ball inside. It is used to detect tilting at small angles.

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

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

4. Project Wiring Diagram:

Note:

How to connect the LED

How to identify the five-color-band 220Ω and 10KΩ resistors

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 successful upload, power it via the USB cable. You will observe: 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 OLED Display

1. Project Introduction:

In life, we can use display modules to do 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 and connect 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 in our accessories. Documentation is being updated. If you find code errors, please contact customer service for repair.

2. Project Components:

ESP32*1 Breadboard*1 OLED Screen*1
Male-to-Female Dupont Wires*4 USB cable*1

3. Component Knowledge:

LCD_128X32_DOT: A pixel display module of 128*32. Its driver chip is ST7567A. The module uses IIC communication. It can not only display English letters and symbols, but also Chinese characters and graphics. When in use, you can also set different sizes for English letters and symbols in the code.

LCD_128X32_DOT Schematic:

LCD_128X32_DOT Technical Parameters:

Display pixels: 128*32 characters

Operating voltage: DC 5V

Operating current: 100mA (5V)

Optimal operating voltage: 5V

Brightness and contrast can be controlled via program commands

4. Project Wiring Diagram:

5. Adding LCD_128x32 Library:

This project code uses the "Adafruit_SSD1306" and "Adafruit_GFX" libraries. If you have not added them yet, please install them before proceeding. Steps to add third-party libraries:

Open Arduino IDE, click "Library Manager icon on the left". In the search box, enter Adafruit_SSD1306 and Adafruit_GFX respectively, click "Install".

Image not found

Image not found

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 initialization successful");

  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 successful upload, power it via the USB cable. You will observe: the LCD 128X32 module displays "Hello World!" on the first line, "0123456789" on the second line, and "Using SoftI2C" on the third line.

Project 17 Small Fan

1. Project Introduction:

In hot summers, we need electric fans to cool down. In this project, we will use the ESP32 to control a DC motor and small fan blade 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 Box*1
NPN Transistor (S8050)*1 PNP Transistor (S8550)*1 1KΩ Resistor*1 Diode*1 Three-blade Soft Propeller*1
Jumper Wires (some) AA Batteries (self-provided)*6 USB cable*1

3. Component Knowledge:

Diode: It is an electronic device made of semiconductor materials (silicon, selenium, germanium, etc.). It has two electrodes: the positive pole, also called the anode; the negative pole, also called the cathode. When a forward voltage is applied across the diode, the diode conducts. When a reverse voltage is applied, the diode is cut off. The conduction and cutoff of a diode are equivalent to a switch being turned on and off.

The gray band end is the negative pole (-), and the other end is the positive pole (+), as shown below:

Diodes have unidirectional conductivity. When conducting, current flows from the anode through the device to the cathode.

Breadboard Power Supply Module:

Description:

This module conveniently provides 3.3V and 5V power to a breadboard. It has a DC2.1 input (DC7-12V) and a 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 compliance: ROHS

Interface Description:

Motor Wiring Description:

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

Image not found

Schematic:

4. Project Wiring Diagram 1:

(This experiment uses S8050 (NPN transistor) to control the motor)

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

5. Project Code 1:

//**********************************************************************
/*
 * File Name  : Small Fan
 * Description : S8050 transistor drives motor operation
 */

void setup() {

  pinMode(15, OUTPUT); // Initialize pin 15 as output
}

void loop() {
  digitalWrite(15, HIGH);   // Turn on motor (HIGH means high level)
  delay(4000);              // Delay 4 seconds
  digitalWrite(15, LOW);    // Lower voltage, turn off motor
  delay(2000);              // Delay 2 seconds
}
//**********************************************************************************

6. Project Phenomenon 1:

Compile and upload the code to the ESP32. After successful upload, connect external power. You will observe: the motor runs for 4 seconds, stops for 2 seconds, repeating this pattern.

7. Project Wiring Diagram 2:

(This experiment uses S8550 (PNP transistor) to control the motor)

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

8. Project Code 2:

//**********************************************************************
/*
 * File Name  : Small Fan
 * Description : S8550 transistor drives motor operation
 */

void setup() {

  pinMode(15, OUTPUT); // Initialize pin 15 as output
}

void loop() {
  digitalWrite(15, LOW);   // Turn on motor (LOW means low level)
  delay(4000);              // Delay 4 seconds
  digitalWrite(15, HIGH);    // Raise voltage, turn off motor
  delay(2000);              // Delay 2 seconds
}
//**********************************************************************************

9. Project Phenomenon 2:

Compile and upload the code to the ESP32. After successful upload, connect external power. You will observe: the motor runs for 4 seconds, stops for 2 seconds, repeating this pattern.

Project 18 Dimming Light

1. Project Introduction:

A potentiometer is a three-terminal resistor with a sliding or rotating contact that forms an adjustable voltage divider. Its working principle is to change the position of the sliding contact on 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 dimming light.

2. Project Components:

ESP32*1 Breadboard*1 Potentiometer*1 Red LED*1
220Ω Resistor*1 USB cable*1 Jumper Wires (some)

3. Component Knowledge:

Potentiometer: A potentiometer is a type of resistor and analog electronic component with two states: 0 and 1 (high level and low level). Different analog values result in data states appearing as linear states from 1 to 1024.

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

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

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

......

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

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

The conversion formula is as follows:

ADC on ESP32 Board:

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

DAC on ESP32 Board:

4. Reading ADC, DAC, and Voltage Values of the Potentiometer:

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

//**********************************************************************************
/*
 * File Name   : Read 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 analogRead() to get the ADC value,
// then use map() to convert the value to 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 successful upload, power it via the USB cable, open the serial monitor, and set the baud rate to 115200. You will observe: the serial monitor window will print the potentiometer's ADC value, DAC value, and voltage value. When you turn the potentiometer knob, the ADC value, DAC value, and voltage value change.

5. Dimming Light Wiring Diagram:

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

6. Project Code:

//**********************************************************************************
/*
 * File Name  : Dimming 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 successful upload, power it via the USB cable. You will observe: turn the potentiometer knob, and the LED's brightness changes accordingly.

Project 19 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, buzzer, and 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 (some)
NPN Transistor (S8050)*1 1kΩ Resistor*1 USB cable*1

3. Component Knowledge:

Flame Sensor (Infrared Receiving Transistor): Fire 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 ESP32) that fire has been detected. The infrared receiving transistor can detect flames and convert flame brightness into a fluctuating level signal. The short pin of the infrared receiving transistor is the negative pole, and the long pin is the positive pole. 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 kept away from direct sunlight, car headlights, and incandescent lamps. It should also not face heat sources (such as radiators, heaters) or air conditioning, to avoid false alarms caused by large ambient temperature changes. It is also susceptible to radio frequency interference.

4. Reading ADC, DAC, and Voltage Values of the Flame Sensor:

First, we use simple code to read and print the ADC value, DAC value, and voltage value of the flame sensor. Refer to the wiring diagram below:

//**********************************************************************************
/*
 * File Name  : Read 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 analogRead() to get the ADC value,
// then use map() to convert the value to 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 successful upload, power it via the USB cable, open the serial monitor, and set the baud rate to 115200. You will observe: the serial monitor window will print the flame sensor's ADC value, DAC value, and voltage value. When a flame approaches the flame sensor, the ADC value, DAC value, and voltage value increase; conversely, they decrease.

5. Flame Alarm Wiring Diagram:

Next, we will use the flame sensor with a 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 adjusted based on actual conditions)

//**********************************************************************************
/*
 * File Name : Flame Alarm
 * 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 flame sensor ADC value
  if (adcVal >= 500) {
    digitalWrite (PIN_BUZZER, HIGH); // Buzzer beeps
    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 successful upload, power it via the USB cable. You will observe: when the flame sensor detects a flame, the LED flashes and the buzzer alarms; otherwise, the LED does not light up and the buzzer does not sound.

Project 20 Night Light

1. Project Introduction:

Sensors or components are ubiquitous in our daily life. For example, some public street lights automatically turn on at night and turn off during the day. Why? In fact, these all utilize 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 achieve this street light effect.

2. Project Components:

ESP32*1 Breadboard*1 Photoresistor*1 Red LED*1
220Ω Resistor*1 10KΩ Resistor*1 Jumper Wires (some) USB cable*1

3. Component Knowledge:

Photoresistor: It is a type of light-sensitive resistor. Its principle is that the resistance decreases when the brightness (light) received on the surface of the photoresistor increases. The resistance of a photoresistor changes with the intensity of the ambient light detected. With this characteristic, we can use a photoresistor to detect light intensity. The photoresistor and its electronic symbol are shown below:

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, the light intensity can be obtained. This project uses the circuit shown on the left above for wiring.

4. Reading ADC, DAC, and Voltage Values of the Photoresistor:

First, we use simple code to read and print the ADC value, DAC value, and voltage value of the photoresistor. Refer to the wiring diagram below:

//**********************************************************************************
/*
 * File Name  : Read Photoresistor Analog Value
 * Description : Basic usage of ADC
 */
#define PIN_ANALOG_IN  36  // Photoresistor pin

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

// In loop(), use analogRead() to get the ADC value,
// then use map() to convert the value to 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 successful upload, power it via the USB cable, open the serial monitor, and set the baud rate to 115200. You will observe: the serial monitor window will print the photoresistor's ADC value, DAC value, and voltage value. When the ambient light intensity around the photoresistor is gradually reduced, 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 dimming light. Now we will make a light-controlled lamp. Their principles are the same: obtain the sensor's analog value via the ESP32, then adjust the brightness of the LED.

6. Project Code:

//**********************************************************************************
/*
 * File Name  : Night Light
 * Description : Control LED brightness via photosensor.
 */
#define PIN_ANALOG_IN    36  // Photosensor 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 successful upload, power it via the USB cable. You will observe: when the ambient light intensity around the photoresistor is reduced, the LED becomes brighter; conversely, the LED becomes dimmer.