from machine import Pin, ADC, Timer
import time
import math
# Setup segment and digit pins
segment_pins = [Pin(i, Pin.OUT) for i in range(7)]
digit_pins = [Pin(i, Pin.OUT) for i in [11, 10, 9, 8]]
dp = Pin(7, Pin.OUT)
# Sensors and button
button_pin = Pin(16, Pin.IN, Pin.PULL_UP)
ADC = machine.ADC(26)
# 7-segment codes
displayCodes = [
0x3F,
0x06,
0x5B,
0x4F,
0x66,
0x6D,
0x7D,
0x07,
0x7F,
0x6F,
0x40,
0x00 # '-' and blank
]
# Globals
display_value = 1234
display_mode = 1 # 0=temp, 1=voltage, 2=light
current_digit = 0
last_button_time = 0
display_timer = Timer()
def read_temperature():
analog_val = ADC.read_u16()
voltage = (analog_val / 65535) * 3.3
BETA = 3950
resistance = 10000 / (3.3 / voltage - 1)
if resistance <= 0:
return voltage
temp = 1 / (math.log(resistance / 10000) / BETA + 1 / 298.15) - 273.15
return temp
last_time =0
debounce=200
def read_voltage():
return round((ADC.read_u16() / 65535) * 3.3, 2)
def read_light():
return int((ADC.read_u16() / 65535) * 100)
def update_display_value():
global display_value
if display_mode == 0:
light = read_light()
display_value = light
print(f"Light: {light}%")
elif display_mode == 1:
voltage = read_voltage()
display_value = int(voltage * 100)
print(f"Voltage: {voltage:.2f} V")
elif display_mode == 2:
temp = read_temperature()
display_value = int(temp * 10)
print(f"Temperature: {temp:.1f} °C")
def display_digit1(digit_value, digit_index, dp_enable=False):
segment_pins[0].value(not ((displayCodes[digit_value] >> 0) & 1))
for i, pin in enumerate(digit_pins):
if i == digit_index:
pin.value(1)
def scan_display(timer=None):
global current_digit
val = abs(display_value)
val_str = str(val)
#for i,d in enumerate(val_str):
# display_digit(int(d),i)
display_digit1(val_str[0])
display_digit2(val_str[1])
display_digit3(val_str[2])
# display_digit4(val_str[4])
#if len(val_str) < 4:
# val_str = (" " * (4 - len(val_str))) + val_str
# elif len(val_str) > 4:
# val_str = val_str[-4:]
# char = val_str[current_digit]
# if char == '-':
# digit = 10
# elif char.isdigit():
# digit = int(char)
# else:
# digit = 11
# dp_enable = (display_mode == 0 and current_digit == 1) or \
# (display_mode == 1 and current_digit == 0)
# display_digit(digit, current_digit, dp_enable)
# current_digit = (current_digit + 1) % 4
def button_handler(pin):
global display_mode, last_button_time
now = time.ticks_ms()
if time.ticks_diff(now, last_button_time) > 300:
#display_mode = (display_mode + 1) % 3
last_button_time = now
print(f"Switched to mode: {display_mode}")
scan_display()
if __name__ == '__main__':
button_pin.irq(trigger=Pin.IRQ_FALLING, handler=button_handler)
#display_timer.init(freq=1000, mode=Timer, callback=scan_display)
#dp.value(0)
print("Ready. Press button to switch modes.")
print("Modes: 0=Temp, 1=Voltage, 2=Light")
try:
while True:
update_display_value()
time.sleep(200)
dp.value(0)
except Exception as e:
print("Error:", e)