Skip to content

Python Tutorial

Project 01 Hello World

1. Project Introduction:

For beginners of ESP32, we will start with some simple things. 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 primary project for ESP32.

2. Project Components:

ESP32*1 USB Cable*1

3. Project Wiring:

In this project, we connect the ESP32 and the computer with a USB cable.

4. Run Code Online:

To run the ESP32 online, you need to connect the ESP32 to the computer. Then you can use the Thonny software to compile or debug programs.

Advantages:

  1. You can use the Thonny software to compile or debug programs.

  2. Through the "Shell" window, you can view the error messages and output results generated during program running, and you can query relevant function information online to help improve the program.

Disadvantages:

  1. To run the ESP32 online, you must connect the ESP32 to a computer and run it together with the Thonny software.

  2. If the ESP32 is disconnected from the computer, the program will not run again when they are reconnected.

Basic Operations:

  1. Open the Thonny software, and click "Open...".

  1. In the new pop-up window, click "This PC".

In the new dialog box, select "Project_01_HelloWorld.py", and click "Open".

Note:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

  1. Click to run the program "Hello World!", and "Welcome keyes" will be printed in the "Shell" window.

5. Exiting Online Run

When running online, click in the Thonny software or press Ctrl+C to exit the program.

Project 02 Turn On LED

1. Project Introduction:

In this project, we will show you how to turn on an LED. We use a digital pin of the ESP32 to turn on the LED so that the LED is lit.

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". It is an electronic device made of semiconductor materials (silicon, selenium, germanium, etc.). It has a positive terminal and a negative terminal. The short leg is the negative terminal and connects to GND; the long leg is the positive terminal and connects to 3.3V or 5V.

(2)Five-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 the resistor, and on the right is the symbol representing the resistor in a circuit. The unit of resistance (R) is the ohm (Ω), 1 mΩ = 1000 kΩ, and 1 kΩ = 1000 Ω.

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

In this kit, we provide 3 five-band resistors with different resistance values. Here we take the 3 five-band resistors as 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 among current, voltage, and resistance can be expressed by the formula: I=U/R. In the figure below, the current currently flowing through R1 is: I = U / R = 3 V / 10 KΩ = 0.0003A = 0.3mA.

Do not connect a resistor with a very low resistance value directly to the two poles of a power supply, as this will make the current too high and damage the electronic components. A resistor has no positive or negative terminals.

(3)Breadboard

A breadboard is an important tool used for building circuits in the laboratory. There are many holes on the breadboard, into which circuit components such as integrated circuits and resistors can be inserted. Mastering the use of the breadboard is one of the important foundations for improving experimental efficiency and reducing the probability of experimental failures. The following is a brief introduction to the structure and usage of the breadboard. A typical breadboard is shown below:

The appearance and internal structure of the breadboard are shown in the figure above. A common minimum-unit breadboard is divided into upper, middle, and lower parts. The upper and lower parts are generally narrow strips composed of one or two rows of sockets, and the middle part is a strip composed of an isolation groove in the middle and 5 rows of sockets on each of the upper and lower sides.

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 the path for power supply introduction. The first row at the top marked with "+" has 10 groups of sockets (all internally connected), all of which are positive; the second row marked with "-" has 10 groups of sockets (all internally connected), all of which are ground. The structure of the first and second rows at the bottom of the breadboard is the same as above. If the entire breadboard is needed, the "+" is usually connected to the "+" with a wire, and the "-" is connected to the "-" with a wire.

The wide strip in the middle is composed of an isolation groove in the middle and 5 rows of sockets on each of the upper and lower sides. The 5 sockets in the same column are connected to each other, while columns and the upper and lower parts of the groove are not connected. The appearance and structure are shown below:

The connection holes of the middle wide strip are divided into upper and lower parts, which are the main working area of the breadboard and are used to plug in 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 upper and lower parts of the groove are not connected. When doing experiments, a small unit composed 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 as the power supply, and one row of the lower narrow strip is used as ground. The middle wide strip is used to connect the circuit. Since the upper and lower parts of the groove are not connected, the integrated block is generally plugged across the groove.

(4) Power Supply

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

4. Project Wiring Diagram:

First, cut 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 with a USB cable.

Note: Avoid any possible short circuit (especially connecting 3.3V and GND)!

Warning: A short circuit may cause a large current in the circuit, overheating the components and causing permanent damage to the hardware.

Note:

How to connect the LED

How to identify the five-band 220Ω resistor

5. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 02 Turn On LED". Then double-click "Project_02_Turn_On_LED.py" with the left mouse button.

from machine import Pin
import time

led = Pin(15, Pin.OUT)   # 创建引脚15为LED对象,设置引脚15为输出

led.value(1)    # led点亮
6. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the LED in the circuit is lit. Press "Ctrl+C" or click to exit the program.

Project 03 LED Flashing

1. Project Introduction:

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

2. Project Components:

ESP32*1 Breadboard*1 Red LED*1
220Ω Resistor*1 Jumper Wires*2 USB Cable*1

3. Project Wiring Diagram:

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

Note: Avoid any possible short circuit (especially connecting 3.3V and GND)!

Warning: A short circuit may cause a large current in the circuit, overheating the components and causing permanent damage to the hardware.

Note:

How to connect the LED

How to identify the five-band 220Ω resistor

4. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 03 LED Flashing". Then double-click "Project_03_LED_Flashing.py" with the left mouse button.

from machine import Pin
import time

led = Pin(15, Pin.OUT)   # 创建引脚15为LED对象,设置引脚15为输出

try:
    while True:
        led.value(1)    # LED点亮
        time.sleep(0.5) # 延时 0.5s
        led.value(0)    # LED熄灭
        time.sleep(0.5) # 延时 0.5s
except:
    pass
5. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click "", and the code starts executing. What you will see is: the LED in the circuit starts flashing. Press "Ctrl+C" or click "" to exit the program.

Project 04 Breathing LED

1. Project Introduction:

In our previous study, we know that an LED has on/off states. Then how do we enter an intermediate state? How do we output an intermediate state to make the LED "half bright"? That is what we are going to learn. A breathing LED means that the LED goes from off to on, and then 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

Analog signals are continuous in both time and value. In contrast, digital signals or discrete-time signals are time sequences composed of a series 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 changing instantly from 0 to 10. However, the value of a digital signal can change instantly, and this change is represented digitally as 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, that is, a series of 0s and 1s. Since a binary signal has only two values (0 or 1), it has great stability and reliability. Finally, analog signals and digital signals can be converted into 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 digital signals into analog signals) very convenient. PWM technology uses digital pins to send square waves of a certain frequency, that is, the output of high level and low level alternating for a period of time. The total time of each group of high level and low level is generally fixed and is called the period (note: the reciprocal of the period is the frequency). The time of high-level output is usually called the pulse width, and 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 lasts, the longer the duty cycle, and the higher the corresponding voltage in the analog signal. The figure below shows the change of the analog signal voltage corresponding to a pulse width of 0%-100% between 0V-3.3V (high level is 3.3V).

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 LEDs or the speed of DC motors, etc. From the above, it can be seen that PWM is not a real analog signal, and the effective value of the voltage is equal to the corresponding analog signal. Therefore, we can control the output power of LEDs and other output modules to achieve different effects.

ESP32 and PWM

Almost all ESP32 input/output pins can be used for PWM (Pulse Width Modulation). These pins can be used to control motors, LED lights, and so on.

4. Project Wiring Diagram:

5. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 04 Breathing LED". Then double-click "Project_04_Breathing_LED.py" with the left mouse button.

import time
from machine import Pin,PWM

# ESP32 PWM引脚输出的方式与传统控制器不同。
# 它可以改变频率和占空比通过配置PWM的参数在初始化阶段。
# 定义GPIO15的输出频率为10000Hz,分配给PWM。

pwm =PWM(Pin(15,Pin.OUT),10000)

try:
    while True:
# 占空比范围为0-1023,因此我们使用第一个for回路控制PWM改变占空比值,使PWM输出0% -100%;
# 使用第二个for回路使PWM输出100%-0%。 
        for i in range(0,1023):
            pwm.duty(i)
            time.sleep_ms(1)

        for i in range(0,1023):
            pwm.duty(1023-i)
            time.sleep_ms(1)  
except:
# 每次使用PWM时,硬件定时器将打开以配合它。
# 因此,每次使用PWM后,都需要调用deinit()来关闭定时器。否则,下次PWM可能无法工作.
    pwm.deinit()

6. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the LED in the circuit gradually brightens from dim, and then gradually dims from bright, just like breathing. Press "Ctrl+C" or click to exit the program.

Project 05 Traffic Lights

1. Project Introduction:

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

2. Project Components:

ESP32*1 Breadboard*1 Red LED*1 Yellow LED*1
Green LED*1 220Ω Resistor*3 Several Jumper Wires USB Cable*1

3. Project Wiring Diagram:

4. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 05 Traffic Lights". Then double-click "Project_05_Traffic_Lights.py" with the left mouse button.

from machine import Pin
import time

led_red = Pin(0, Pin.OUT)  # 创建引脚0为红色led对象,设置引脚0为输出
led_yellow = Pin(2, Pin.OUT)  # 创建引脚2为黄色led对象,设置引脚2为输出
led_green = Pin(15, Pin.OUT) # 创建引脚15为绿色led对象,设置引脚15为输出

while True:
    led_red.value(1)  # 红色LED点亮
    time.sleep(5)   # 延时 5s
    led_red.value(0) # 红色LED熄灭
    led_yellow.value(1)
    time.sleep(0.5)
    led_yellow.value(0)
    time.sleep(0.5)
    led_yellow.value(1)
    time.sleep(0.5)
    led_yellow.value(0)
    time.sleep(0.5)
    led_yellow.value(1)
    time.sleep(0.5)
    led_yellow.value(0)
    time.sleep(0.5)
    led_green.value(1)
    time.sleep(5) 
    led_green.value(0) 
5. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: 1. First, the red light is on for 5 seconds, then turns off; 2. Second, the yellow light flashes 3 times, then turns off; 3. Then, the green light is on for 5 seconds, then turns off; 4. The above steps 1-3 keep repeating. Press "Ctrl+C" or click to exit the program.

Project 06 RGB LED

1. Project Introduction:

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

2. Project Components:

ESP32*1 Breadboard*1 RGB LED*1
220Ω Resistor*3 Several Jumper Wires USB Cable*1

3. Component Knowledge:

Displays mostly follow the RGB color standard. All colors on a computer screen are composed of the three colors red, green, and blue mixed 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 of 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:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 06 RGB LED". Then double-click "Project_06_RGB_LED.py" with the left mouse button.

# 导入Pin、PWM和random库.
from machine import Pin, PWM
from random import randint
import time

# 配置GPIO15, GPIO2, GPIO0的输出方式为PWM输出,PWM频率为10000Hz.
pins = [0, 2, 15]

pwm0 = PWM(Pin(pins[0]),10000)  
pwm1 = PWM(Pin(pins[1]),10000)
pwm2 = PWM(Pin(pins[2]),10000)

#定义一个函数来设置RGBLED的颜色.
def setColor(r, g, b):
    pwm0.duty(1023-r)
    pwm1.duty(1023-g)
    pwm2.duty(1023-b)

try:
    while True:
        red   = randint(0, 1023) 
        green = randint(0, 1023)
        blue  = randint(0, 1023)
        setColor(red, green, blue)
        time.sleep_ms(200)
except:
    pwm0.deinit()
    pwm1.deinit()
    pwm2.deinit()
6. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the RGB LED starts displaying random colors. Press "Ctrl+C" or click to exit the program.

Project 07 Flowing Water Light

1. Project Introduction:

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

2. Project Components:

ESP32*1 Breadboard*1 Red LED*10
220Ω Resistor*10 Several Jumper Wires USB Cable*1

3. Project Wiring Diagram:

4. Project Code:

This project is to design and make a flowing water light. These 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 operation for all 10 LEDs until the last LED turns off. This process is repeated to achieve the "movement" of flowing water.

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 07 Flowing Water Light". Then double-click "Project_07_Flowing_Water_Light.py" with the left mouse button.

from machine import Pin
import time

# 使用阵列定义10个连接点阵屏的GPIO端口,便于操作。.
pins = [22, 21, 19, 18, 17, 16, 4, 0, 2, 15]
# 使用两个for循环分别从左到右打开led,然后从右到左打开led
def showLed():
    for pin in pins:
        print(pin)
        led = Pin(pin, Pin.OUT)
        led.value(1)
        time.sleep_ms(100)
        led.value(0)
        time.sleep_ms(100)        
    for pin in reversed(pins):
        print(pin)
        led = Pin(pin, Pin.OUT)
        led.value(1)
        time.sleep_ms(100)
        led.value(0)
        time.sleep_ms(100)

while True:
    showLed()
5. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the 10 LEDs light up from left to right, and then return from right to left. Press "Ctrl+C" or click to exit the program.

Project 08 1-Digit Digital Tube

1. Project Introduction:

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

2. Project Components:

ESP32*1 Breadboard*1 1-Digit Digital Tube*1
220Ω Resistor*8 Several Jumper Wires USB Cable*1

3. Component Knowledge:

1-Digit Digital Tube Display Principle: A digital tube display is a semiconductor light-emitting device. Its basic unit is a light-emitting diode (LED). Digital tube displays can be divided into 7-segment digital tubes and 8-segment digital tubes according to the number of segments. An 8-segment digital tube has one more LED unit than a 7-segment one (used for the 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 digital tubes and common-cathode digital tubes.

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

In a common-anode 7-segment digital tube, all the anodes (positive terminals) 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 segment of the digital tube is composed 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 an ordinary common-cathode 1-digit digital tube. As we mentioned above, you should connect the common cathode to GND, and to light up a segment LED, you can set its associated pin to HIGH.

4. Project Wiring Diagram:

Note: The direction of the seven-segment digital tube inserted into the breadboard is consistent with the wiring diagram, with an extra dot at the bottom right corner.

5. Project Code:

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

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 08 1-Digit Digital Tube". Then double-click "Project_08_One_Digit_Digital_Tube.py" with the left mouse button.

from machine import Pin
import time

a = Pin(16, Pin.OUT)
b = Pin(4, Pin.OUT)
c = Pin(5, Pin.OUT)
d = Pin(18, Pin.OUT)
e = Pin(19, Pin.OUT)
f = Pin(22, Pin.OUT)
g = Pin(23, Pin.OUT)
dp = Pin(17, Pin.OUT)

pins = [Pin(id,Pin.OUT) for id in [16, 4, 5, 18, 19, 22, 23, 17]]

def show(code):
    for i in range(0, 8):
        pins[i].value(~code & 1)
        code = code >> 1

## 选择0 ~ 9之间的编码
mask_digits = [0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8,0x80, 0x90]
for code in reversed(mask_digits):
    show(code)
    time.sleep(1)

6. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the 1-digit digital tube will display numbers from 9 to 0. Press "Ctrl+C" or click to exit the program.

Project 09 4-Digit Digital Tube

1. Project Introduction:

The 4-digit digital tube is a very practical display device. The display of electronic clocks, the scorers on courts, and the number of people in parks all need it. 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 4-digit digital tube to display four-digit numbers.

2. Project Components:

ESP32*1 Breadboard*1 4-Digit Digital Tube*1
220Ω Resistor*8 Several Jumper Wires USB Cable*1

3. Component Knowledge:

4-Digit Digital Tube: 4-digit digital tubes come in common-anode and common-cathode types. The display principle is similar to that of a 1-digit digital tube: both use 8 GPIO ports to control the display segments, that is, 8 LEDs. However, since this one has 4 digits, 4 additional GPIO ports are needed to control the digit selection terminals, that is, to select which single digital tube is lit. The switching of digits is very fast, so the naked eye cannot distinguish it, making it look like multiple digital tubes are displaying at the same time.

Our 4-digit digital tube is common-cathode.

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

The figure below is the internal wiring schematic of the 4-digit digital tube.

4. Project Wiring Diagram:

5. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 09 4-Digit Digital Tube". Then double-click "Project_09_Four_Digit_Digital_Tube.py" with the left mouse button.

from machine import Pin
import time

# 数码管每个数字引脚
a = Pin(18, Pin.OUT)
b = Pin(13, Pin.OUT)
c = Pin(2, Pin.OUT)
d = Pin(16, Pin.OUT)
e = Pin(17, Pin.OUT)
f = Pin(19, Pin.OUT)
g = Pin(0, Pin.OUT)
dp = Pin(4, Pin.OUT)

# 位选引脚
G1 = Pin(21, Pin.OUT)
G2 = Pin(22, Pin.OUT)
G3 = Pin(14, Pin.OUT)
G4 = Pin(15, Pin.OUT)

# 数码管a到dp对应的引脚
d_Pins = [a, b, c, d, e, f, g, dp]
# 数码管位选引脚
w_Pins = [G1, G2, G3, G4]

# 数码管0-F码值
number = [
    [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]   # .
]

def display(g, n):
    """
    显示功能:g的取值范围是1~4,n的取值范围是0~9
    """
    # 关闭所有段
    for pin in d_Pins:
        pin.value(0)

    # 选择要显示的位
    for i in range(len(w_Pins)):
        if i + 1 == g:
            w_Pins[i].value(0)  # 选中对应位(低电平有效)
        else:
            w_Pins[i].value(1)  # 其他位关闭

    # 显示数字的各个段
    for i in range(8):
        d_Pins[i].value(number[n][i])

def show_number(num):
    """
    显示一个4位数(0-9999)
    """
    # 将数字分解为千位、百位、十位、个位
    thousands = num // 1000
    hundreds = (num % 1000) // 100
    tens = (num % 100) // 10
    ones = num % 10

    # 动态扫描显示
    display(1, thousands)
    time.sleep_ms(2)
    display(2, hundreds)
    time.sleep_ms(2)
    display(3, tens)
    time.sleep_ms(2)
    display(4, ones)
    time.sleep_ms(2)

def setup():
    """
    初始化所有引脚
    """
    # 引脚已经在创建时设置为OUTPUT,这里只是确认
    for pin in d_Pins:
        pin.init(Pin.OUT)
    for pin in w_Pins:
        pin.init(Pin.OUT)

def loop():
    """
    主循环:从0到9999循环显示
    """
    while True:
        # 从0到9999循环
        for num in range(10000):
            # 每个数字显示125个周期,总共约1秒
            # 每个显示周期是4个位 * 2ms = 8ms
            # 125 * 8ms = 1000ms = 1秒
            for _ in range(125):
                show_number(num)

# 程序入口
if __name__ == "__main__":
    setup()
    loop()
6. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the 4-digit digital tube displays numbers and repeats these actions in an infinite loop. Press "Ctrl+C" or click to exit the program.

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 transportation departure indicators, and many other devices. In this project, we will use the ESP32 to control an 8x8 dot matrix display to gradually light up the LEDs on the dot matrix.

2. Project Components:

ESP32*1 Breadboard*1 8×8 Dot Matrix Display*1
220Ω Resistor*8 Several Jumper Wires USB Cable*1

3. Component Knowledge:

8×8 Dot Matrix: It is composed of 64 LEDs, and has two types: row common-anode and row common-cathode. Our module is row common-anode, that is, each row has a line connecting the positive terminals of the LEDs together, and each column connects the negative terminals of the LEDs together, as shown in the figure below:

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

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

4. Project Wiring Diagram:

5. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 10 8×8 Dot Matrix Display". Then double-click "Project_09_Four_Digit_Digital_Tube.py" with the left mouse button.

from machine import Pin
import time

#定义行引脚并设置为输出.
row1 = Pin(14, Pin.OUT)
row2 = Pin(26, Pin.OUT)
row3 = Pin(4, Pin.OUT)
row4 = Pin(27, Pin.OUT)
row5 = Pin(19, Pin.OUT)
row6 = Pin(16, Pin.OUT)
row7 = Pin(18, Pin.OUT)
row8 = Pin(17, Pin.OUT)
#定义列的引脚并设置为输出
col1 = Pin(32, Pin.OUT)
col2 = Pin(21, Pin.OUT)
col3 = Pin(22, Pin.OUT)
col4 = Pin(12, Pin.OUT)
col5 = Pin(0, Pin.OUT)
col6 = Pin(13, Pin.OUT)
col7 = Pin(33, Pin.OUT)
col8 = Pin(25, Pin.OUT)

#将列的引脚设置为低电平
col1.value(0)
col2.value(0)
col3.value(0)
col4.value(0)
col5.value(0)
col6.value(0)
col7.value(0)
col8.value(0)

#由于点阵的列被设置为低电平,因此当该行的引脚处于高电平时,点阵的对应行将亮起
def Row(d):
    if(d ==1):
        row1.value(1)  #点亮第一条线
    if(d ==2):
        row2.value(1)  #点亮第二条线
    if(d ==3):
        row3.value(1)
    if(d ==4):
        row4.value(1)
    if(d ==5):
        row5.value(1)
    if(d ==6):
        row6.value(1)
    if(d ==7):
        row7.value(1)
    if(d ==8):
        row8.value(1)

#关闭格子
def off():
    row1.value(0)
    row2.value(0)
    row3.value(0)
    row4.value(0)
    row5.value(0)
    row6.value(0)
    row7.value(0)
    row8.value(0) 

try:
    print("test...")
    while True:
         for num in range(1,10):  #逐行点亮格子
             Row(num)
             if(num == 9):  #因为晶格只有8行,我在这里限定一下,等于9
                off()      #关闭格子
             time.sleep(0.2)

except:
    pass

6. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the 8x8 dot matrix display gradually lights up. Press "Ctrl+C" or click to exit the program.

Project 11 Shift Register Controls 8 LEDs

1. Project Introduction:

In previous projects, we have already learned how to light up an LED.

Usually, the number of IO ports on a development board is limited. If a large number of devices need to be controlled, the situation of insufficient IO ports will arise. For example, in Project 2, each light requires one IO port to control it. If multiple lights need to be controlled, the IO ports will be exhausted. To deal with this scenario, we introduce a shift register to expand the IO ports. In this project, we will use the ESP32, the 74HC595 chip, and LEDs to make a flowing water 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 Several Jumper Wires USB Cable*1

3. Component Knowledge:

74HC595N Chip: Simply speaking, it has an 8-bit shift register and a storage register, as well as a tri-state output function. The shift register and the storage register are synchronized to different clocks. Data is input at the rising edge of the shift register clock SCK and enters the storage register at the rising edge of the storage register clock RCK. If the two clocks are connected together, the shift register is always one pulse earlier than the storage register. The shift register has a serial shift input (SI) and a serial output (SQH) for cascading. The 8-bit shift register can be reset asynchronously (active-low reset). The storage register has an 8-bit tri-state parallel bus output. When the output enable (OE) is enabled (active low), the data in the storage register is output to the pins (bus) of the 74HC595N.

Img

Pin Description:

Pin: Pin Description:
Pin 13 OE It is an output enable pin, used to ensure whether the data in the latch is input to the Q0-Q7 pins. At low level, no high level is output. In this experiment, we connect it directly to GND to keep the data output at low level.
Pin 14 SI/DS This is the pin through which the 74HC595 receives data, that is, the serial data input. Only one bit can be input at a time, so after 8 consecutive inputs, a byte can be formed.
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 keep 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 time, the data is output in parallel from the Q0~Q7 ports.
Pin 9 SQH The pin is a serial output pin, specifically used for chip cascading, connecting to the SI terminal of the next 74HC595.
Q0--Q7 (Pin 15, Pins 1-7) Eight-bit parallel output terminals, which can directly control the 8 segments of a digital tube.

4. Project Wiring Diagram:

Note: Pay attention to the insertion direction of the 74HC595N chip.

5. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 11 Shift Register Controls 8 LEDs". Select "my74HC595.py", right-click and select "Upload to/", wait for "my74HC595.py" to be uploaded to the ESP32, then double-click "Project_11_74HC595N_Controls_8_LEDs.py" with the left mouse button.

# 导入time和my74HC595库.
from my74HC595 import Chip74HC595
import time

# 创建Chip74HC595对象并配置引脚
chip = Chip74HC595(14, 12, 13)
# ESP32-14: 74HC595-DS(14)
# ESP32-12: 74HC595-STCP(12)
# ESP32-13: 74HC595-SHCP(11)

#第一个for循环使LED从左到右分别点亮
#而第二个for循环使它从右向左分别点亮.
while True:
    x = 0x01
    for count in range(8):
        chip.shiftOut(1, x)
        x = x<<1;
        time.sleep_ms(300)
    x = 0x01
    for count in range(8):
        chip.shiftOut(0, x)
        x = x<<1
        time.sleep_ms(300)
6. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the 8 LEDs start flashing in a flowing water pattern. Press "Ctrl+C" or click to exit the program.

Project 12 Active Buzzer

1. Project Introduction:

An active buzzer is a sound-producing component. It is widely used as a sound-producing element in computers, printers, alarms, electronic toys, telephones, timers, and so on. It has an internal vibration source and can continuously emit a buzzing sound by simply connecting a 5V power supply. 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 Several Jumper Wires USB Cable*1

3. Component Knowledge:

Active Buzzer: It has a simple oscillator circuit inside, which can convert a constant DC current into a pulse signal of a specific frequency. Once the active buzzer receives a high level, it will produce sound. In contrast, a passive buzzer is an integrated electronic buzzer with no internal vibration source, and it must be driven by a 2K-5K square wave instead of a DC signal. The appearances of these two buzzers are very similar, but a buzzer with a green circuit board is a passive buzzer, while the one with black tape is an active buzzer. A passive buzzer cannot distinguish positive polarity, while an active buzzer can, as shown below:

Transistor: Since the buzzer requires a large current, the GPIO output capability of the ESP32 cannot meet the requirement. Here, an NPN transistor is needed 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): the base (b), the collector (c), and the emitter (e). When current flows between "be", "ce" will allow several times the current to pass through (transistor amplification). At this time, the transistor operates in the amplification region. When the current between "be" exceeds a certain value, "ce" will no longer allow the current to increase, and 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 the transistor, it is often used as a switch in digital circuits. Since the current output capability of a microcontroller is very weak, we will use a transistor to amplify the 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, the 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, the 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: In this circuit, the power supply of the buzzer is 5V. Under a 3.3V power supply, the buzzer can work, but the loudness will be reduced.

5. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 12 Active Buzzer". Then double-click "Project_12_Active_Buzzer.py" with the left mouse button.

from machine import Pin
import time

buzzer = Pin(15, Pin.OUT)   # 创建引脚15为蜂鸣器对象,设置引脚15为输出

try:
    while True:
        buzzer.value(1)    # 蜂鸣器鸣叫
        time.sleep(0.5) # 延时 0.5s
        buzzer.value(0)    # 蜂鸣器关闭
        time.sleep(0.5) # 延时 0.5s
except:
    pass
6. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the active buzzer emits a "beep-beep" sound. Press "Ctrl+C" or click to exit the program.

Project 13 Passive Buzzer

1. Project Introduction

In the previous project, we studied the active buzzer, which can only emit one kind of sound, which may make you feel monotonous. This project will learn about another 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 Several Jumper Wires USB Cable*1

3. Component Knowledge:

Passive Buzzer: It is an integrated electronic buzzer with no internal vibration source. It must be driven by a 2K-5K square wave instead of a DC signal. Its appearance is very similar to that of the active buzzer, but a buzzer with a green circuit board is a passive buzzer, while the one with black tape is an active buzzer. A passive buzzer cannot distinguish positive polarity, while an active buzzer can, as shown in the figure below:

Transistor: Please refer to Project 12.

4. Project Wiring Diagram:

5. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 13 Passive Buzzer". Then double-click "Project_13_Passive_Buzzer.py" with the left mouse button.

from machine import Pin, PWM
import time

# 初始化无源蜂鸣器(GPIO15,硬件PWM输出精确方波)
buzzer = PWM(Pin(15), freq=500, duty=512)

while True:
    #输出500HZ频率声音,持续约160ms(80次×2ms)
    buzzer.freq(500)
    time.sleep(0.16)
    #输出250HZ频率声音,持续约400ms(100次×4ms)
    buzzer.freq(250)
    time.sleep(0.4)
6. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the passive buzzer emits an alarm sound. Press "Ctrl+C" or click to exit the program.

Project 14 Mini Table Lamp

1. Project Introduction:

Do 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 table lamp.

2. Project Components:

ESP32*1 Breadboard*1 Button*1
10KΩ Resistor*1 Red LED*1 220Ω Resistor*1
Button Cap*1 Several Jumper Wires USB Cable*1

3. Component Knowledge:

Button: A button can control the on/off of a circuit. When a button is connected into a circuit, the circuit is disconnected when the button is not pressed, and the circuit is connected as soon as the button is pressed, but it is disconnected again after being released. But why does it conduct only when pressed? This has to start from the internal structure of the button. Before being pressed, the current cannot pass from one end of the button to the other; when pressed, the metal piece inside the button connects the two sides to let the current pass through.

The internal structure of the button is as shown in the figure: . Before the button is pressed, 1 and 2 are conductive, and 3 and 4 are also conductive, but 1-3, 1-4, 2-3, or 2-4 are disconnected (not conductive); only when the button is pressed are 1-3, 1-4, 2-3, or 2-4 conductive. When designing circuits, the button switch is one of the most commonly used components.

Button Schematic:

What is button bouncing? The switch circuit we imagine is "press the button - conduct immediately" and "press again - disconnect immediately", but this is not the case in reality.

Buttons usually use mechanical elastic switches, and at the moment the mechanical contacts disconnect and close (usually about 10ms), a series of bounces occur due to elastic action, causing the button switch to not connect the circuit stably and immediately when closed, nor to disconnect completely and instantly when opened.

Then how do we eliminate button bouncing?

There are two common methods to eliminate bouncing: the software method and the hardware method. Here we focus on the convenient and simple software method. We already know that the bouncing time caused by elastic inertia is about 10ms. Using a delay command to postpone the execution time of the command can achieve the effect of eliminating bouncing.

So we add a 0.02-second delay in the code to realize the button debouncing function.

4. Project Wiring Diagram:

Note:

How to connect the LED

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

5. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 14 Mini Table Lamp". Then double-click "Project_14_Mini_Table_Lamp.py" with the left mouse button.

from machine import Pin
import time

led = Pin(4, Pin.OUT) # 创建引脚4为LED对象,设置引脚4为输出                  
button = Pin(15, Pin.IN, Pin.PULL_UP) #Pin15创建引脚15按钮对象,设置GP15为输入

#定义一个函数并将其命名为reverseGPIO(),用于反转LED的输出电平
def reverseGPIO():
    if led.value():
        led.value(0)     #LED熄灭
    else:
        led.value(1)     #LED点亮

try:
    while True:
        if not button.value():
            time.sleep_ms(20)
            if not button.value():
                reverseGPIO()
                while not button.value():
                    time.sleep_ms(20)
except:
    pass
6. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: press the button, and the LED lights up; when the button is released, the LED is still on. Press the button again, and the LED turns off; when the button is released, the LED stays off. Doesn't it look like a small table lamp? Press "Ctrl+C" or click to exit the program.

Project 15 Simulated Hourglass

1. Project Introduction:

Ancient people had no electronic clocks, so they invented the hourglass to measure time. The capacity on both sides of the hourglass is relatively large, with fine sand placed on one side and a very small channel in the middle. When the hourglass is upright with the side containing the fine sand on top, due to gravity, the fine sand flows down through the channel to the other side of the hourglass. When all the fine sand has flowed to the bottom, it is turned over, and the number of times it repeats in a day is recorded. The next day, the approximate time of the day can be known by the number of times the hourglass has flowed repeatedly. In this lesson, we will use the ESP32 to control a tilt switch and LED lights to simulate an hourglass and make an electronic hourglass.

2. Project Components:

||||| | :--: | :--: | :--: | :--: | :--: | |ESP321|Breadboard1|Tilt Switch1|10KΩ Resistor1| ||| || |Red LED4|220Ω Resistor1|Several Jumper Wires|USB Cable*1|

3. Component Knowledge:

A tilt switch is also called a digital switch or a ball switch, and there is a metal ball inside it. It is used to detect small-angle tilting.

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

In the program, we judge whether the switch is on or off based on whether the voltage value of the analog port is greater than 2.5V (512 binary).

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-band 220Ω resistor and the five-band 10KΩ resistor

5. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 15 Simulated Hourglass". Then double-click "Project_15_Tilt_And_LED.py" with the left mouse button.

from machine import Pin
import time

led1 = Pin(16, Pin.OUT) # 创建引脚2为LED对象,设置引脚2为输出
led2 = Pin(17, Pin.OUT) # 创建引脚17为LED对象,设置引脚17为输出
led3 = Pin(18, Pin.OUT) # 创建引脚18为LED对象,设置引脚18为输出
led4 = Pin(19, Pin.OUT) # 创建引脚19为LED对象,设置引脚19为输出
Tilt_Sensor = Pin(15,Pin.IN) #创建引脚15倾斜传感器对象,设置GP15为输入

while True:
    if(Tilt_Sensor.value() == 0) : #如果倾斜传感器的值为0时
        led1.value(1) # led1 点亮
        time.sleep_ms(200)#延时
        led2.value(1) # led2 点亮
        time.sleep_ms(200)#延时
        led3.value(1) # led3 点亮
        time.sleep_ms(200)#延时
        led4.value(1) # led4 点亮
        time.sleep_ms(200)#延时
    else :           #如果倾斜传感器的值为1时
        led4.value(0) # led4 熄灭
        time.sleep_ms(200)#延时
        led3.value(0) # led3 熄灭
        time.sleep_ms(200)#延时
        led2.value(0) # led2 熄灭
        time.sleep_ms(200)#延时
        led1.value(0) # led1 熄灭
        time.sleep_ms(200)#延时

6. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: tilt the breadboard to a certain angle, and the LEDs light up one by one. When returning to the previous angle, the LEDs turn off one by one. Just like an hourglass, as time goes by, the sand leaks out. Press "Ctrl+C" or click to exit the program.

Project 16 OLED Display

1. Project Introduction:

In life, we can use modules such as displays 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.

Next, we will use the LCD_128X32_DOT module as a display and connect it to the ESP32 control board. We will use the ESP32 board to control the LCD_128X32_DOT display to show various English letters, common symbols, and numbers.

Note: We have upgraded the LCD screen in the accessory to the more commonly used OLED screen, and the documentation is being updated gradually. If you find a code running error, please contact customer service for a fix.

2. Project Components:

ESP32*1 Breadboard*1 OLED Display*1
Several DuPont Wires USB Cable*1

3. Component Knowledge:

LCD_128X32_DOT: A liquid crystal screen module with 128*32 pixels, whose driver chip is ST7567A. The module uses IIC communication. It can display not only English letters and symbols, but also Chinese characters and patterns. When in 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

Working voltage: DC 5V

Working current: 100mA (5V)

Optimal module working voltage: 5V

Brightness and contrast can be controlled by program instructions

4. Project Wiring Diagram:

5. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 17 OLED Display". Upload the two py files to the ESP32 respectively, then double-click "Project_16_I2C_128_64_OLED.py" with the left mouse button.

from machine import Pin, SoftI2C
import ssd1306
import time

# 初始化 I2C 和 OLED
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=400000)
display = ssd1306.SSD1306_I2C(128, 64, i2c)

# 清除显示
display.fill(0)
display.show()

# 显示文本
display.text('Hello World!', 0, 0, 1)
display.text('0123456789', 0, 16, 1)
display.text('Using SoftI2C', 0, 32, 1)
display.show()
6. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the 128X32 LCD module display shows "Hello World!" on the first line, "0123456789" on the second line, and "Using SoftI2C" on the third line. Press "Ctrl+C" or click to exit the program.

Project 17 Small Fan

1. Project Introduction:

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

2. Project Components:

ESP32*1 Breadboard*1 DC Motor*1 Breadboard Power Module*1 6-cell AA Battery Holder*1
NPN Transistor (S8050)*1 PNP Transistor (S8550)*1 1KΩ Resistor*1 Diode*1 Three-blade Soft Propeller*1
Several Jumper Wires AA Battery (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 terminal, also called the anode, and the negative terminal, also called the cathode. When a forward voltage is applied across the two poles of a diode, the diode conducts; when a reverse voltage is applied, the diode blocks. The conduction and blocking of a diode is equivalent to the on and off of a switch.

The end with the gray ring is the negative terminal, and the other end is the positive terminal, as shown in the figure below:

A diode has unidirectional conductivity. When conducting, the current direction is from the anode through the tube to the cathode.

Breadboard Power 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 has a USB Type C interface power input.

Specifications:

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

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

Max power: 2.5W

Dimensions: 53mmx26.3mm

Environmental attribute: ROHS

Interface Description:

Motor Wiring Description:

Because the current batch of motors uses a standard interface and cannot be directly inserted into the breadboard, please use two DuPont wires to insert into the white interface to complete this experiment.

图片不存在

Schematic:

4. Project Wiring Diagram 1:

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

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

5. Project Code 1:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 17 Small Fan". Then double-click "Project_17.1_ Small_Fan.py" with the left mouse button.

from machine import Pin
import time

motor = Pin(15, Pin.OUT)   # create S8050 object from Pin 15, Set Pin 15 to output

try:
    while True:
        motor.value(1)    # Set motor turn on
        time.sleep(4) # Sleep 4s
        motor.value(0)    # Set motoe turn off
        time.sleep(2) # Sleep 2s
except:
    pass

6. Project Result 1:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the small fan turns for 4 seconds, stops for 2 seconds, and repeats in this pattern. Press "Ctrl+C" or click to exit the program.

7. Project Wiring Diagram 2:

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

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

8. Project Code 2:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 17 Small Fan". Then double-click "Project_17.2_ Small_Fan.py" with the left mouse button.

from machine import Pin
import time

motor = Pin(15, Pin.OUT)   # create S8550 object from Pin 15, Set Pin 15 to output

try:
    while True:
        motor.value(0)    # Set motor turn on
        time.sleep(4) # Sleep 4s
        motor.value(1)    # Set motoe turn off
        time.sleep(2) # Sleep 2s
except:
    pass
9. Project Result 2:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the small fan turns for 4 seconds, stops for 2 seconds, and repeats in this pattern. Press "Ctrl+C" or click to exit the program.

Project 18 Dimmable Light

1. Project Introduction:

A potentiometer is a three-terminal resistor with a sliding or rotating contact, which 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 entire length of the resistance, 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 Potentiometer*1 Red LED*1
220Ω Resistor*1 USB Cable*1 Several Jumper Wires

3. Component Knowledge:

Potentiometer: A potentiometer is a type of resistor and analog electronic component. It has two states, 0 and 1 (high level and low level). When the analog value differs, its data state presents a linear state such as 1 ~ 1024.

ADC: ADC is an electronic integrated circuit used to convert analog signals (such as voltage) into digital or binary form composed of 1s and 0s. The range of the ADC on our ESP32 is 12 bits, which means the resolution is 2^12=4096. It indicates that a range (3.3V) will be evenly divided into 4096 parts, and the range of the analog value corresponds to the ADC value. Therefore, the more bits the ADC has, the denser the analog division, and the higher the final conversion accuracy.

Section 1: An analog value within the range of 0V—(3.3/4095)V corresponds to digital 0;

Section 2: An analog value within the range of (3.3/4095)V—2*(3.3/4095)V corresponds to digital 1;

......

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

DAC: The reversal of this process requires a DAC, a digital-to-analog converter. Digital I/O ports can output high level and low level (0 or 1), but cannot output an intermediate voltage value, which is where DAC is useful. The ESP32 has two 8-bit precision 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 value is 3.3/256×1V; when the digital value is 128, the output voltage value is 3.3/256 ×128=1.65V. The higher the precision of the DAC, the higher the precision of the output voltage value.

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 serial numbers and analog pin definitions are shown in the table below:

DAC on the ESP32 Board:

4. Read the ADC Value, DAC Value, and Voltage Value of the Potentiometer:

We connect the potentiometer to the analog IO port of the ESP32 to read the ADC value, DAC value, and voltage value of the potentiometer. For the wiring, please refer to the wiring diagram below:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 22 Dimmable Light". Then double-click "Project_18.1_Read_Potentiometer_Analog_Value.py" with the left mouse button.

# 导入 Pin, ADC 和DAC 库.
from machine import ADC,Pin,DAC
import time

# 打开并配置0-3.3V的ADC
adc=ADC(Pin(36))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)

#每0.1秒读取一次ADC值,将ADC值转换为DAC值并输出,
#并将这些数据打印到“Shell”. 
try:
    while True:
        adcVal=adc.read()
        dacVal=adcVal//16
        voltage = adcVal / 4095.0 * 3.3
        print("ADC Val:",adcVal,"DACVal:",dacVal,"Voltage:",voltage,"V")
        time.sleep(0.1)
except:
    pass
Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the "Shell" window under the Thonny IDE will print the ADC value, DAC value, and voltage value of the potentiometer. When you rotate the potentiometer handle, the ADC value, DAC value, and voltage value change. Press "Ctrl+C" or click to exit the program.

5. Wiring Diagram of the Dimmable Light:

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

6. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 22 Dimmable Light". Then double-click "Project_18.2_Dimming_Light.py" with the left mouse button.

from machine import Pin,PWM,ADC
import time

pwm =PWM(Pin(15,Pin.OUT),1000)
adc=ADC(Pin(36))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_10BIT)

try:
    while True:
        adcValue=adc.read()
        pwm.duty(adcValue)
        print(adc.read())
        time.sleep_ms(100)
except:
    pwm.deinit()
7. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: rotate the potentiometer handle, and the brightness of the LED changes accordingly. Press "Ctrl+C" or click to exit the program.

Project 19 Flame Alarm

1. Project Introduction:

Fire is a terrible disaster, and fire alarm systems are very useful in houses, 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 Several Jumper Wires
NPN Transistor (S8050)*1 1kΩ Resistor*1 USB Cable*1

3. Component Knowledge:

Flame Sensor (infrared receiver triode): A flame emits a certain degree of IR light, which is invisible to the human eye, but our infrared receiver triode can detect it and remind the microcontroller (such as the ESP32) that a fire has been detected. The infrared receiver triode can detect the flame and then convert the flame brightness into a fluctuating level signal. The short pin of the infrared receiver triode 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 in the figure below:

Note: The flame sensor should avoid direct irradiation from sunlight, car headlights, and incandescent lamps, and should 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 interference from radio frequency radiation.

4. Read the ADC Value, DAC Value, and Voltage Value of the Flame Sensor:

We first use a simple code to read and print the ADC value, DAC value, and voltage value of the flame sensor. For the wiring, please refer to the wiring diagram below:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 23 Flame Alarm". Then double-click "Project_19.1_Read_Analog_Value_Of_Flame_Sensor.py" with the left mouse button.

# 导入 Pin, ADC and DAC 库.
from machine import ADC,Pin,DAC
import time

# 打开并配置0-3.3V的ADC 
adc=ADC(Pin(36))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)

# 每0.1秒读取一次ADC值,将ADC值转换为DAC值并输出,
# 并将这些数据打印到“Shell”. 
try:
    while True:
        adcVal=adc.read()
        dacVal=adcVal//16
        voltage = adcVal / 4095.0 * 3.3
        print("ADC Val:",adcVal,"DACVal:",dacVal,"Voltage:",voltage,"V")
        time.sleep(0.1)
except:
    pass
Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the "Shell" window under the Thonny IDE will print the ADC value, DAC value, and voltage value read by the flame sensor. When the flame approaches the flame sensor, the ADC value, DAC value, and voltage value increase; conversely, the ADC value, DAC value, and voltage value decrease. Press "Ctrl+C" or click to exit the program.

5. Wiring Diagram of the Flame Alarm:

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 reset by yourself according to the actual situation)

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 23 Flame Alarm". Then double-click "Project_19.2_Flame_Alarm.py" with the left mouse button.

from machine import ADC, Pin
import time

# 打开并配置0-3.3V的ADC 
adc=ADC(Pin(36))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)
# 创建引脚15为LED对象,设置引脚15为输出
led = Pin(15, Pin.OUT) 
# 创建引脚4为蜂鸣器对象,设置引脚4为输出
buzzer = Pin(4, Pin.OUT)   

# 如果火焰传感器检测到火焰,蜂鸣器将发出蜂鸣声
#,当模拟值大于500时,LED闪烁
# 否则,蜂鸣器不响,LED熄灭

while True:
    adcVal=adc.read()
    if adcVal >500:
        buzzer.value(1) # 蜂鸣器鸣叫
        led.value(1)    # LED点亮
        time.sleep(0.5) # 延时 0.5s
        buzzer.value(0) # 蜂鸣器关闭
        led.value(0)    
        time.sleep(0.5) # 延时 0.5s
    else:
        buzzer.value(0) # 蜂鸣器关闭
        led.value(0)    # LED熄灭
7. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: when the flame sensor detects a flame, the LED flashes and the buzzer alarms; otherwise, the LED is off and the buzzer is silent. Press "Ctrl+C" or click to exit the program.

Project 20 Night Light

1. Project Introduction:

Sensors or components are ubiquitous in our daily lives. For example, some public street lights automatically turn on at night and automatically turn off during the day. Why? In fact, these all use a kind of photosensitive element, a component that can sense the intensity of external 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 is very simple. In this experiment, we use the ESP32 to control an LED to realize the effect of such a street light.

2. Project Components:

ESP32*1 Breadboard*1 Photoresistor*1 Red LED*1
220Ω Resistor*1 10KΩ Resistor*1 Several Jumper Wires USB Cable*1

3. Component Knowledge:

Photoresistor: It is a light-sensitive resistor. Its principle is that the brightness (light) received on the surface of the photoresistor reduces the resistance, and the resistance value of the photoresistor changes with the strength of the detected ambient light. With this characteristic, we can use the photoresistor to detect light intensity. The photoresistor and its electronic symbol are as follows:

The following circuit is used to detect the change in the resistance value of the photoresistor:

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

4. Read the ADC Value, DAC Value, and Voltage Value of the Photoresistor:

We first use a simple code to read and print the ADC value, DAC value, and voltage value of the photoresistor. For the wiring, please refer to the wiring diagram below:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 24 Night Light". Then double-click "Project_20.1_Read_Photosensitive_Analog_Value.py" with the left mouse button.

# 导入 Pin, ADC 和 DAC 库.
from machine import ADC,Pin,DAC
import time

# 打开并配置0-3.3V的ADC
adc=ADC(Pin(36))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)

#每0.1秒读取一次ADC值,将ADC值转换为DAC值并输出,
#并将这些数据打印到“Shell”. 
try:
    while True:
        adcVal=adc.read()
        dacVal=adcVal//16
        voltage = adcVal / 4095.0 * 3.3
        print("ADC Val:",adcVal,"DACVal:",dacVal,"Voltage:",voltage,"V")
        time.sleep(0.1)
except:
    pass
Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the "Shell" window under the Thonny IDE will print the ADC value, DAC value, and voltage value read by the photoresistor. When the light intensity in the environment where the photoresistor is located gradually decreases, the ADC value, DAC value, and voltage value gradually increase; conversely, the ADC value, DAC value, and voltage value gradually decrease. Press "Ctrl+C" or click to exit the program.

5. Wiring Diagram of the Light-Controlled Lamp:

We made a small dimmable light earlier, and now we will make a light-controlled lamp. Their principles are the same: obtain the analog value of the sensor through the ESP32, and then adjust the brightness of the LED.

6. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 24 Night Light". Then double-click "Project_20.2_Night_Lamp.py" with the left mouse button.

from machine import Pin,PWM,ADC
import time

pwm =PWM(Pin(15,Pin.OUT),1000)
adc=ADC(Pin(36))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_10BIT)

try:
    while True:
        adcValue=adc.read()
        pwm.duty(adcValue)
        print(adc.read())
        time.sleep_ms(100)
except:
    pwm.deinit()
7. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: when the light intensity in the environment where the photoresistor is located decreases, the LED becomes brighter; conversely, the LED becomes dimmer. Press "Ctrl+C" or click to exit the program.

Project 21 Temperature Instrument

1. Project Introduction:

A thermistor is a resistor whose resistance value depends on temperature and temperature changes, and it is widely used in devices such as gardening and home alarm systems. Therefore, we can use this characteristic to make a thermometer.

2. Project Components:

ESP32*1 Breadboard*1 OLED Display*1 Thermistor*1
10KΩ Resistor*1 Several DuPont Wires USB Cable*1 Several Jumper Wires

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 characteristic of the thermistor to detect temperature intensity. The thermistor and its electronic symbol are shown below.

The relationship between the resistance value of the thermistor 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 the n-th power of e;

B is the temperature index;

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

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

4. Read the Thermistor Value:

First, we learn how the thermistor reads the current ADC value, voltage value, and temperature value and prints them out. Please connect the wires according to the wiring diagram below:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 29 Temperature Instrument". Then double-click "Project_21.1_Read_the_thermistor_analog_value.py" with the left mouse button.

from machine import Pin, ADC
import time
import math

#设置 ADC
adc=ADC(Pin(36))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)

try:
    while True:
        adcValue = adc.read()
        voltage = adcValue / 4095 * 3.3
        Rt = 10 * voltage / (3.3-voltage)
        tempK = (1 / (1 / (273.15+25) + (math.log(Rt/10)) / 3950))
        tempC = (tempK - 273.15)
        print("ADC value:",adcValue,"  Voltage:",voltage,"V","  Temperature: ",tempC,"C");
        time.sleep(1)
except:
    pass
Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the "Shell" window under the Thonny IDE will continuously display the current ADC value, voltage value, and temperature value of the thermistor. Try pinching the thermistor with your index finger and thumb (do not touch the wires) for a short period of time, and you should see the temperature value increase. Press "Ctrl+C" or click to exit the program.

5. Wiring Diagram of the Temperature Instrument:

6. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 29 Temperature Instrument". Select "lcd128_32.py" and "lcd128_32_fonts.py" respectively, right-click and select "Upload to/", and wait for "lcd128_32.py" and "lcd128_32_fonts.py" to be uploaded to the ESP32. Then double-click "Project_21.2_Temperature_Instrument.py" with the left mouse button.

from machine import Pin, ADC, I2C
import machine
import time
import math
import lcd128_32_fonts
from lcd128_32 import lcd128_32

#设置 ADC
adc=ADC(Pin(36))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)

#i2c配置
clock_pin = 22
data_pin = 21
bus = 0
i2c_addr = 0x3f
use_i2c = True

def scan_for_devices():
    i2c = machine.I2C(bus,sda=machine.Pin(data_pin),scl=machine.Pin(clock_pin))
    devices = i2c.scan()
    if devices:
        for d in devices:
            print(hex(d))
    else:
        print('no i2c devices')

try:
    while True:
        adcValue = adc.read()
        voltage = adcValue / 4095 * 3.3
        Rt = 10 * voltage / (3.3-voltage)
        tempK = (1 / (1 / (273.15+25) + (math.log(Rt/10)) / 3950))
        tempC = int(tempK - 273.15)        
        if use_i2c:
            scan_for_devices()
            lcd = lcd128_32(data_pin, clock_pin, bus, i2c_addr)  
        lcd.Clear()
        lcd.Cursor(0, 0)
        lcd.Display("Voltage:")
        lcd.Cursor(0, 8)
        lcd.Display(str(voltage))
        lcd.Cursor(0, 20)
        lcd.Display("V")
        lcd.Cursor(2, 0)
        lcd.Display("Temperature:")
        lcd.Cursor(2, 12)
        lcd.Display(str(tempC))
        lcd.Cursor(2, 15)
        lcd.Display("C")
        time.sleep(0.5)
except:
    pass
7. Project Result:

Make sure the ESP32 is connected to the computer, and click .

Click , and the code starts executing. What you will see is: the LCD 128X32 DOT screen displays the voltage value of the thermistor and the temperature value of the current environment. Press "Ctrl+C" or click to exit the program.

Project 22 WiFi Working Mode

In today's era of rapid technological development, the method of uniformly controlling intelligent devices through mobile phones has gradually gained people's favor. This method uses a microcontroller to establish a connection between the mobile phone and the intelligent device through a WiFi module and the Internet, thereby realizing remote control of the intelligent device. Our development board comes with a WiFi module. In this chapter, we will focus on the WiFi development of the ESP32.

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

Project 22.1: WIFI Station Mode

1. Experiment Components:

USB Cable x1 ESP32 x1

2. Experiment Wiring:

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

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 through the WiFi connection. As shown in the figure below, the PC and the router are already connected. If the ESP32 wants to communicate with the PC, the PC and the router need to be connected.

4. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 22 WiFi Working Mode". Then double-click "Project_22.1_WiFi_Station_Mode.py" with the left mouse button.

import time
import network # 导入 network 库.

ssidRouter     = 'ChinaNet-2.4G-0DF0' # 输入路由器名称
passwordRouter = 'ChinaNet@233' # 输入路由器密码

def STA_Setup(ssidRouter,passwordRouter):
    print("Setup start")
    sta_if = network.WLAN(network.STA_IF) # 设置ESP32为“Station模式”.
    if not sta_if.isconnected():
        print('connecting to',ssidRouter)
  # 激活ESP32的站模式,向路由器发起连接请求
 # 并输入连接密码.      
        sta_if.active(True)
        sta_if.connect(ssidRouter,passwordRouter)
  #等待ESP32与路由器连接成功.      
        while not sta_if.isconnected():
            pass
  # 在Shell中打印分配给ESP32-WROVER的IP地址. 
    print('Connected, IP address:', sta_if.ifconfig())
    print("Setup End")

try:
    STA_Setup(ssidRouter,passwordRouter)
except:
    sta_if.disconnect()
5. Project Result:

Because the router names and passwords differ from place to place, before running the code, the user needs to enter the correct router name and password in the red box shown in the figure above.

After confirming that the router name and password are correctly entered, click , and the code starts executing. Wait for the ESP32 to connect to your router, and the IP address assigned to the ESP32 by the router will be printed in the "Shell" window.

Project 22.2: WIFI AP Mode

1. Experiment Components & Wiring:

The experiment components and wiring are the same as those in Project 22.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 the hotspot. If a mobile phone or PC needs to communicate with the ESP32, it must connect to the ESP32's hotspot. Communication can only be performed after establishing a connection through the ESP32.

3. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 22 WiFi Working Mode". Then double-click "Project_22.2_WiFi_AP_Mode.py" with the left mouse button.

import network #导入 network 库.

#请输入正确的路由器名称和密码.
ssidAP         = 'ESP32_Wifi' #输入AP名称
passwordAP     = '12345678'  #输入AP密码

local_IP       = '192.168.1.147'
gateway        = '192.168.1.1'
subnet         = '255.255.255.0'
dns            = '8.8.8.8'

#配置ESP32为AP模式.
ap_if = network.WLAN(network.AP_IF)

def AP_Setup(ssidAP,passwordAP):
    ap_if.ifconfig([local_IP,gateway,subnet,dns])
    print("Setting soft-AP  ... ")
    ap_if.config(essid=ssidAP,authmode=network.AUTH_WPA_WPA2_PSK, password=passwordAP)
    ap_if.active(True)
    print('Success, IP address:', ap_if.ifconfig())
    print("Setup End\n")

try:
    AP_Setup(ssidAP,passwordAP)
except:
    print("Failed, please disconnect the power and restart the operation.")
    ap_if.disconnect()
4. Project Result:

Before the program code runs, you can make any changes to the AP name and password of the ESP32 in the red box as shown in the figure above. Of course, by default, you can also leave it unchanged.

Click , and the code starts executing, turning on the AP function of the ESP32. The access point information will be printed in the "Shell" window.

When observing the information printed by the serial monitor, open the mobile phone's WiFi scanning function, and you can see that the ssid_AP on the ESP32 is called "ESP32_Wifi" in this program code. You can enter the password "12345678" to connect to it, or you can modify its AP name and password by modifying the program code.

Project 35.3: WIFI AP+Station Mode

1. Experiment Components & Wiring:

The experiment components and wiring are the same as those in Project 22.1: WIFI Station Mode and Project 22.2: WIFI AP Mode above.

2. Component Knowledge:

AP+Station Mode: Besides the AP mode and Station mode, the ESP32 can also use the AP mode and Station mode at the same time. This mode includes the functions of the previous two modes. Turn on the Station mode of the ESP32 and connect it to the router network, and it can communicate with the Internet through the router. At the same time, turn on its AP mode to create a hotspot network. Other WiFi devices can choose to connect to the router network or the hotspot network to communicate with the ESP32.

3. Project Code:

The code used in this tutorial is saved at the path: "..\program-code\python-code".

You can move the code anywhere. For example, we save the code on Drive D, at the path D:\2. Project Tutorial.

Open the "Thonny" software, click "This PC" → "D:" → "2. Project Tutorial" → "Project 22 WiFi Working Mode". Then double-click "Project_22.3_WiFi_Station+AP_Mode.py" with the left mouse button.

import network #导入 network 库.

ssidRouter     = 'ChinaNet-2.4G-0DF0' #输入路由器名称
passwordRouter = 'ChinaNet@233' #输入路由器密码

ssidAP         = 'ESP32_Wifi'#输入AP名称
passwordAP     = '12345678' #输入AP密码

local_IP       = '192.168.4.147'
gateway        = '192.168.1.1'
subnet         = '255.255.255.0'
dns            = '8.8.8.8'

sta_if = network.WLAN(network.STA_IF)
ap_if = network.WLAN(network.AP_IF)

def STA_Setup(ssidRouter,passwordRouter):
    print("Setting soft-STA  ... ")
    if not sta_if.isconnected():
        print('connecting to',ssidRouter)
        sta_if.active(True)
        sta_if.connect(ssidRouter,passwordRouter)
        while not sta_if.isconnected():
            pass
    print('Connected, IP address:', sta_if.ifconfig())
    print("Setup End")

def AP_Setup(ssidAP,passwordAP):
    ap_if.ifconfig([local_IP,gateway,subnet,dns])
    print("Setting soft-AP  ... ")
    ap_if.config(essid=ssidAP,authmode=network.AUTH_WPA_WPA2_PSK, password=passwordAP)
    ap_if.active(True)
    print('Success, IP address:', ap_if.ifconfig())
    print("Setup End\n")

try:
    AP_Setup(ssidAP,passwordAP)    
    STA_Setup(ssidRouter,passwordRouter)
except:
    sta_if.disconnect()
    ap_if.idsconnect()
4. Project Result:

It is similar to Project 22.1 and Project 22.2 above. Before running the code, you need to modify ssidRouter, passwordRouter, ssidAP, and passwordAP, as shown in the red boxes in the figure above. After making sure the code is correctly modified, click , and the code starts executing. The "Shell" window will display as follows:

Open the WiFi search function of the mobile phone, and you can see that the ssid_AP on the ESP32 is called.