在物联网和嵌入式系统中,使用微控制器(如ESP32)来控制硬件设备是一种常见的做法。在本教程中,我们将探讨如何使用ESP32控制一个七段数码管。
所需材料
- ESP32开发板
- 杜邦线若干
- 一个七段数码管
- 面包板
连接步骤
-
将ESP32开发板的GPIO引脚连接到七段数码管的每个数字和点上。注意我们使用共阴极接法,具体连接方式如下:
- 单片机GND -> 数码管的GNDPin
- 单片机Pin13-> 数码管的a端口
- 单片机Pin12-> 数码管的b端口
- 单片机Pin14-> 数码管的c端口
- 单片机Pin27-> 数码管的e端口
- 单片机Pin25-> 数码管的f端口
- 单片机Pin33-> 数码管的g端口
- 单片机Pin32-> 数码管的dot端口
-
将杜邦线连接起来,形成一个完整的电路。
代码实现
首先,我们需要导入必要的库,并定义一些常量。
import machine
import time
# 定义引脚对象
a = machine.Pin(13, machine.Pin.OUT)
b = machine.Pin(12, machine.Pin.OUT)
c = machine.Pin(14, machine.Pin.OUT)
d = machine.Pin(27, machine.Pin.OUT)
e = machine.Pin(26, machine.Pin.OUT)
f = machine.Pin(25, machine.Pin.OUT)
g = machine.Pin(33, machine.Pin.OUT)
dot = machine.Pin(32, machine.Pin.OUT)
# 将对应的引脚对象存放到列表中
number_led = [a, b, c, d, e, f, g]
接下来,我们定义一个字典,用于存储数字和对应的七段数码管显示编码。
number_dict = {
0: "1111110",
1: "0110000",
2: "1101101",
3: "1111001",
4: "0110011",
5: "1011011",
6: "1011111",
7: "1110000",
8: "1111111",
9: "1111011",
"open": "1111111",
"close": "0000000"
}
然后,我们定义一个函数show_number
,用于显示给定的数字。如果需要显示小数点,可以传入True
作为第二个参数。
def show_number(number, switch):
if number_dict.get(number): # 判断number是否为字典中的key
i = 0
for num in number_dict.get(number): # 取出value 遍历字符串
if num == '1':
number_led[i].value(1)
else:
number_led[i].value(0)
i += 1
if switch:
dot.value(1)
else:
dot.value(0)
最后,我们编写主函数main
,在其中使用循环来显示数字。
def main():
# 数码管循环显示1~9
while True:
for i in range(0, 10):
show_number(i, True)
time.sleep(1)
for i in range(9, -1, -1):
show_number(i, True)
time.sleep(1)
效果演示
运行程序后,数码管会循环显示数字1到9,并在每次显示之间暂停1秒。具体效果如下:
wokwi官网项目链接
##完整代码
import machine
import time
a = machine.Pin(13, machine.Pin.OUT)
b = machine.Pin(12, machine.Pin.OUT)
c = machine.Pin(14, machine.Pin.OUT)
d = machine.Pin(27, machine.Pin.OUT)
e = machine.Pin(26, machine.Pin.OUT)
f = machine.Pin(25, machine.Pin.OUT)
g = machine.Pin(33, machine.Pin.OUT)
dot = machine.Pin(32, machine.Pin.OUT)
#将对应的引脚对象存放到链表中
number_led = [a, b, c, d, e, f, g]
number_dict = {
0: "1111110",
1: "0110000",
2: "1101101",
3: "1111001",
4: "0110011",
5: "1011011",
6: "1011111",
7: "1110000",
8: "1111111",
9: "1111011",
"open": "1111111",
"close": "0000000"
}
#数码管显示函数 number为数字 switch为小数点
def show_number(number,switch):
if number_dict.get(number): #判断number是否为字典中的key
i=0
for num in number_dict.get(number): #取出value 遍历字符串
if num=='1':
number_led[i].value(1)
else:
number_led[i].value(0)
i+=1
if switch:
dot.value(1)
else:
dot.value(0)
def main():
#数码管循环显示1~9
while True:
for i in range(0,10):
show_number(i,True)
time.sleep(1)
for i in range(9,-1,-1):
show_number(i,True)
time.sleep(1)
if __name__ == "__main__":
main()