import machine
import time
DISPLAY_COUNT ,DECIMAL_PRECISION ,DEBOUNCE_TIME,READINGS_COUNT = 4,1,200,16
VOLTAGE_REFERENCE ,ADC_RESOLUTION = 3.3,65535
display_value ,last_button_press_time,timer = 0,0,None
digit_list_hex = [0x40, 0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10]
segment_pins ,display_select_pins ,Analog ,button = [],[],None,None
def read_sensor_voltage():
return ((Analog.read_u16()) * VOLTAGE_REFERENCE / ADC_RESOLUTION)
def scan_display(timer):
global display_value
# Convert the display_value to a string
value_str = "{:.3f}".format(display_value)
# Remove the decimal point and get the first 4 digits
value_str = value_str.replace('.', '')[:4]
# Create a list of digits with leading zeros if necessary
digits = [int(value_str[i]) if i < len(value_str) else 0 for i in range(DISPLAY_COUNT)]
# Determine if the decimal point should be enabled
dp_enable = (digits[0] != 0)
# Display the digits on the corresponding 7-segment displays
for i, digit in enumerate(digits):
display_digit(digit, i, dp_enable)
def display_digit(digit_value, digit_index, dp_enable=False):
# Ensure the value is valid
if 0 <= digit_value < len(digit_list_hex):
# Deselect all display select pins
for pin in display_select_pins:
pin.value(0)
# Set the segments according to the digit value
mask = digit_list_hex[digit_value]
for i, pin in enumerate(segment_pins):
pin.value((mask >> i) & 1)
# Set the DP if it's enabled
segment_pins[7].value(int(not dp_enable))
# Activate the relevant display select pin
display_select_pins[digit_index].value(1) if 0 <= digit_index < DISPLAY_COUNT else None
def enable_display_timer():
global timer
timer = machine.Timer()
timer.init(period=1, mode=machine.Timer.PERIODIC, callback=scan_display)
def read_analogue_voltage(pin):
global display_value, last_button_press_time
current_time = time.ticks_ms()
# Debouncing the button
if current_time - last_button_press_time > DEBOUNCE_TIME:
last_button_press_time = current_time
display_value = read_sensor_voltage()
# Print the voltage on the serial
print("Voltage: {:.0f} mV".format(display_value * 1000))
def setup():
global segment_pins, display_select_pins, Analog, button
# Define pins for the segments and displays
pin_numbers = [0, 1, 2, 3, 4, 5, 6, 7, 11, 10, 9, 8]
segment_pins = [machine.Pin(pin_number, machine.Pin.OUT) for pin_number in pin_numbers[:8]]
display_select_pins = [machine.Pin(pin_number, machine.Pin.OUT) for pin_number in pin_numbers[8:]]
# Initialize ADC for analog reading
Analog = machine.ADC(26)
# Initialize button with interrupt for analog reading
button = machine.Pin(16, machine.Pin.IN)
button.irq(trigger=machine.Pin.IRQ_FALLING, handler=read_analogue_voltage)
# Enable the display timer
enable_display_timer()
if __name__ == '__main__':
setup()