# imports
import machine
import math
import time
#######################################
# Pin and constant definitions
#######################################
# MCU pins
SEGMENT_PINS = [machine.Pin(0), machine.Pin(1), machine.Pin(2), machine.Pin(3), machine.Pin(4), machine.Pin(5), machine.Pin(6),machine.Pin(7)]
DIGIT_PINS = [machine.Pin(11), machine.Pin(10), machine.Pin(8), machine.Pin(9)]
BUTTON_PIN = machine.Pin(16, machine.Pin.IN, machine.Pin.PULL_UP)
ADC_PIN = machine.Pin(26)
# Constants
DEBOUNCE_TIME = 200
SCAN_INTERVAL = 10
#######################################
# Global variables
#######################################
display_value = 0
#######################################
# Function definitions
#######################################
def read_analogue_voltage(pin):
global display_value
# Read analogue voltage level 16 times and average the readings
total = 0
for _ in range(16):
total += ADC_PIN.read_u16()
average = total / 16
# Calculate the corresponding analogue value
voltage = (average / 65535) * 3.3
# Update the display_value global variable
display_value = round(voltage, 3)
# Debounce the button press
time.sleep_ms(DEBOUNCE_TIME)
def disable_display_timer():
# Disable the timer that triggers scanning 7 segment displays
pass
def enable_display_timer():
# Enable the timer that triggers scanning 7 segment displays
pass
def scan_display(timer_int):
global display_value
# Read the value stored in the display_value global variable
value = display_value
# Display the value on the 7-segment displays
for i in range(4):
digit_value = int(value * 1000) % 10
display_digit(digit_value, i, dp_enable=(i == 1))
value /= 10
def display_digit(digit_value, digit_index, dp_enable=False):
# Display the given value on the display with the specified index
segment_pins = SEGMENT_PINS
digit_pins = DIGIT_PINS
# Set the segment pins
for i in range(7):
segment_pins[i].value((digit_value >> i) & 1)
# Set the digit pin
digit_pins[digit_index].value(1)
# Set the decimal point pin
if dp_enable:
segment_pins[7].value(1)
else:
segment_pins[7].value(0)
def display_digit(digit_value, digit_index, dp_enable=False):
# Display the given value on the display with the specified index
segment_pins = SEGMENT_PINS
digit_pins = DIGIT_PINS
# Set the segment pins
for i in range(7):
segment_pins[i].value((digit_value >> i) & 1)
# Set the digit pin
digit_pins[digit_index].value(1)
# Set the decimal point pin
if dp_enable:
segment_pins[7].value(1)
else:
segment_pins[7].value(0)
def display_value_test():
# Test available 7-segment displays
for i in range(4):
display_digit(i, i)
def setup():
# Set up GPIO/ADC pins, timers and interrupts
global BUTTON_PIN, ADC_PIN
BUTTON_PIN.irq(trigger=machine.Pin.IRQ_FALLING, handler=read_analogue_voltage)
ADC_PIN = machine.ADC(machine.Pin(26))
if __name__ == '__main__':
setup()
display_value_test()
while True:
scan_display(None)
time.sleep_ms(SCAN_INTERVAL)