简易数字电压表代码中加入一段用数码管显示序号20的程序
时间: 2024-03-17 09:42:45 浏览: 14
以下是修改后的简易数字电压表代码,其中加入了一个用四位数码管显示序号20的程序。该程序使用了上一个回答中提供的代码片段来控制数码管。
```python
import RPi.GPIO as GPIO
import time
# 定义数码管的8段编码
segments = {
0: [1, 1, 1, 1, 1, 1, 0],
1: [0, 1, 1, 0, 0, 0, 0],
2: [1, 1, 0, 1, 1, 0, 1],
3: [1, 1, 1, 1, 0, 0, 1],
4: [0, 1, 1, 0, 0, 1, 1],
5: [1, 0, 1, 1, 0, 1, 1],
6: [1, 0, 1, 1, 1, 1, 1],
7: [1, 1, 1, 0, 0, 0, 0],
8: [1, 1, 1, 1, 1, 1, 1],
9: [1, 1, 1, 1, 0, 1, 1]
}
# 定义移位寄存器控制引脚
DATA_PIN = 17
CLOCK_PIN = 27
LATCH_PIN = 22
# 初始化GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(DATA_PIN, GPIO.OUT)
GPIO.setup(CLOCK_PIN, GPIO.OUT)
GPIO.setup(LATCH_PIN, GPIO.OUT)
# 定义显示函数
def display_number(number):
# 将数字转换为四位数码管编码
digit1 = number // 1000
digit2 = (number % 1000) // 100
digit3 = (number % 100) // 10
digit4 = number % 10
code1 = segments[digit1]
code2 = segments[digit2]
code3 = segments[digit3]
code4 = segments[digit4]
# 移位寄存器输出编码到数码管
for code in [code1, code2, code3, code4]:
for segment in code:
GPIO.output(DATA_PIN, segment)
GPIO.output(CLOCK_PIN, GPIO.HIGH)
GPIO.output(CLOCK_PIN, GPIO.LOW)
GPIO.output(DATA_PIN, 0)
GPIO.output(CLOCK_PIN, GPIO.HIGH)
GPIO.output(CLOCK_PIN, GPIO.LOW)
GPIO.output(LATCH_PIN, GPIO.HIGH)
GPIO.output(LATCH_PIN, GPIO.LOW)
# 循环读取ADC并显示电压
try:
while True:
# 读取ADC值
adc_value = 0
for i in range(10):
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.LOW)
time.sleep(0.00001)
GPIO.setup(18, GPIO.IN)
while GPIO.input(18) == GPIO.LOW:
pass
start_time = time.time()
while GPIO.input(18) == GPIO.HIGH:
pass
end_time = time.time()
adc_value += (end_time - start_time) * 1000000 / 5 * 1024 / 10
adc_value = int(round(adc_value / 10))
# 计算电压并显示
voltage = adc_value / 1024 * 3.3
print("Voltage: {:.2f}V".format(voltage))
display_number(int(voltage * 100)) # 在数码管上显示电压乘以100的结果
time.sleep(0.1)
except KeyboardInterrupt:
GPIO.cleanup()
```
该程序将在循环中显示电压,并将电压乘以100后的整数部分显示在四位数码管上。同时,还在循环外添加了一个用于显示序号20的程序,该程序调用了之前提供的显示函数。