# imports
import machine
import math
import time
#######################################
# Pin and constant definitions
#######################################
ANALOGUE_INPUT_PIN = 26
DISPLAY_COUNT = 4
MEASUREMENT_COUNT = 16
DECIMAL_PRECISION = 3
ADC_RANGE = float((math.pow(2, 16) - 1))
#######################################
# Global variables
#######################################
display_value = 0
segment_pins = []
display_select_pins = []
analogue_voltage_pin = None
current_display_index = DISPLAY_COUNT -1 # to keep track of which digit is currently being displayed
display_timer = None
prev_analogue_voltage = -1
#######################################
# Function definitions
#######################################
# Function to read the ADC pin and
# to convert the digital value to a voltage level in the 0-3.3V range
# This function updates the value of the display_value global variable
def read_analogue_voltage(pin): # We can use the pin parameter if needed
global display_value, prev_disp_val, display_timer
global prev_analogue_voltage, DECIMAL_PRECISION
# Take MEASUREMENT_COUNT measurements and average them
total_value = 0
for _ in range(MEASUREMENT_COUNT):
total_value += pin.read_u16()
average_value = total_value // MEASUREMENT_COUNT
# Convert the average digital value to an analogue voltage value
analogue_voltage = round((average_value / ADC_RANGE) * 3.3, DISPLAY_COUNT - 1)
if analogue_voltage != prev_analogue_voltage:
prev_analogue_voltage = analogue_voltage
new_display_value = int(analogue_voltage * math.pow(10, DECIMAL_PRECISION))
# Temperature Reading
# When using the NTC, change the line below to
# if True
# then observe the temperature values on displays.
# Note that the imlementation displays the absolute value.
# So, both -24.0C and 24.0C appear as 24.0.
if False:
DECIMAL_PRECISION = 2
temp = 0
try:
# Use the formula from
# https://docs.wokwi.com/parts/wokwi-ntc-temperature-sensor
temp = round(1 / (math.log(1 / (ADC_RANGE / average_value - 1)) / 3950 + 1.0 / 298.15) - 273.15, 1)
print(f'temp: {temp} C')
except:
pass
new_display_value = int(temp * math.pow(10, DECIMAL_PRECISION))
max_val = math.pow(10, DISPLAY_COUNT) - 1
if new_display_value > max_val:
print(f'warn: {new_display_value} exceeds {max_val}, clipping')
new_display_value = max_val
if display_value != new_display_value:
print(f'voltage: {analogue_voltage} mV')
time.sleep(0.1)
# Function display the given value on the display with the specified index
# dp_enable specifies if the decimal pooint should be on or off
# Function to setup GPIO/ADC pins, timers and interrupts
def setup():
global analogue_voltage_pin, voltage_value
global display_timer
analogue_voltage_pin = machine.ADC(ANALOGUE_INPUT_PIN)
if __name__ == '__main__':
setup()
#display_value_test()
while True:
read_analogue_voltage(analogue_voltage_pin)
time.sleep(0.5)