# -*- coding: utf-8 -*-
from machine import Pin
import onewire
import ds18x20
import time
# ====== 硬件配置 ====== :ml-citation{ref="1,3" data="citationList"}
# 5641AS数码管引脚定义(共阴型)
# 位选引脚(控制哪一位显示)
DIGITS = [Pin(5, Pin.OUT), # 第1位
Pin(18, Pin.OUT), # 第2位
Pin(19, Pin.OUT), # 第3位
Pin(21, Pin.OUT)] # 第4位
# 段选引脚(控制显示数字形状)
SEGMENTS = [Pin(13, Pin.OUT), # a段
Pin(12, Pin.OUT), # b段
Pin(14, Pin.OUT), # c段
Pin(27, Pin.OUT), # d段
Pin(26, Pin.OUT), # e段
Pin(25, Pin.OUT), # f段
Pin(33, Pin.OUT), # g段
Pin(32, Pin.OUT)] # 小数点dp
# 数字编码(共阴型,0表示点亮)
NUMBERS = {
0: [0,0,0,0,0,0,1,1], # 0
1: [1,0,0,1,1,1,1,1], # 1
2: [0,0,1,0,0,1,0,1], # 2
3: [0,0,0,0,1,1,0,1], # 3
4: [1,0,0,1,1,0,0,1], # 4
5: [0,1,0,0,1,0,0,1], # 5
6: [0,1,0,0,0,0,0,1], # 6
7: [0,0,0,1,1,1,1,1], # 7
8: [0,0,0,0,0,0,0,1], # 8
9: [0,0,0,0,1,0,0,1], # 9
'-': [1,1,1,1,1,1,0,1], # 负号
'E': [0,1,1,0,0,0,0,1] # 错误标识
}
# ====== DS18B20初始化 ====== :ml-citation{ref="3" data="citationList"}
ds_pin = Pin(15) # 温度传感器接GPIO15(示例引脚,可修改)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
roms = ds_sensor.scan()
# ====== 温度读取函数 ====== :ml-citation{ref="3,4" data="citationList"}
def read_temp():
try:
ds_sensor.convert_temp()
time.sleep_ms(750) # 等待温度转换
temp = ds_sensor.read_temp(roms)
return round(temp, 1)
except:
return None # 传感器异常返回空值
# ====== 数码管显示函数 ====== :ml-citation{ref="1,2" data="citationList"}
def display_number(number, decimal_pos=-1):
# 异常显示处理
if number is None:
segments = NUMBERS['E'] + NUMBERS['E'][:-1]
for i in range(4):
DIGITS[i].value(0 if i==0 else 1) # 仅第一位显示E
for seg, val in zip(SEGMENTS, segments):
seg.value(val)
time.sleep_ms(5)
return
# 数字分解处理
str_num = f"{abs(number):4.1f}".replace(' ','').zfill(4)
最新发布