from machine import Pin, ADC, Timer
import time
import math
Seven_Segment = [0, 1, 2, 3, 4, 5, 6]
digit_pins = [11, 10, 9, 8]
dp = Pin(7, Pin.OUT)
button = 16
pot_pin = 26
temp_pin = 27
light_pin = 28
adc_pot = ADC(Pin(pot_pin))
adc_temp = ADC(Pin(temp_pin))
adc_light = ADC(Pin(light_pin))
displayCodes =[
0x3F,
0x06,
0x5B,
0x4F,
0x66,
0x6D,
0x7D,
0x07,
0x7F,
0x6F,
0x40,
0x00
]
display_buffer = [' ', ' ', ' ', ' ']
current_digit = 0
last_button_press = 0
debouncing = 200
mode = 0
segments = [Pin(d, Pin.OUT) for d in Seven_Segment]
digits = [Pin(d, Pin.OUT) for d in digit_pins]
display_timer = Timer()
def read_voltage():
raw = adc_pot.read_u16()
voltage = (raw / 65535) * 3.3
return voltage # float
def read_temperature():
BETA = 3950
raw = adc_temp.read_u16()
voltage = raw * 3.3 / 65535
resistance = 10000 / (3.3 / voltage - 1)
temp = 1 / (math.log(resistance / 10000) / BETA + 1 / 298.15) - 273.15
return int(temp)
def read_light():
raw = adc_light.read_u16()
percent = (raw / 65535) * 100
return int(percent)
def update_display(voltage=None, temp=None, light=None):
global display_buffer
dp.value(1) # Turn OFF decimal point by default
if voltage is not None:
val = f"{voltage:.2f}".replace('.', '')[:3].rjust(3)
display_buffer = list(val + ' ')
dp.value(0) # Turn ON decimal point between digit 2 and 3
elif temp is not None:
val = str(temp).rjust(3)
display_buffer = list(val)
elif light is not None:
val = str(light).rjust(3)
display_buffer = list(val)
def display_digit(timer):
global current_digit
for d in digits:
d.value(0)
char = display_buffer[current_digit]
pattern = displayCodes(char, 0x00)
for i in range(7):
segments[i].value((pattern >> i) & 1)
if current_digit == 2 and dp.value() == 0:
dp.value(0)
else:
dp.value(1)
digits[current_digit].value(1)
current_digit = (current_digit + 1) % 4
def button_handler(pin):
global last_button_press, mode
now = time.ticks_ms()
if time.ticks_diff(now, last_button_press) > debouncing:
last_button_press = now
mode = (mode + 1) % 3
if mode == 0:
val = read_voltage()
print(f"Voltage: {val:.2f} V")
update_display(voltage=val)
elif mode == 1:
val = read_temperature()
print(f"Temperature: {val} °C")
update_display(temp=val)
elif mode == 2:
val = read_light()
print(f"Light: {val}%")
update_display(light=val)
def enable_display_timer():
display_timer.init(period=5, mode=Timer.PERIODIC, callback=display_digit)
def setup():
enable_display_timer()
button_pin = Pin(button, Pin.IN, Pin.PULL_DOWN)
button_pin.irq(trigger=Pin.IRQ_RISING, handler=button_handler)
print("Ready. Press the button to switch display mode.")
if __name__ == '__main__':
setup()
try:
while True:
time.sleep(0.1)
except KeyboardInterrupt:
display_timer.deinit()
for digit in digits:
digit.value(0)
print("Program stopped.")