import machine
import math
import time
#######################################
# Pin and constant definitions
#######################################
ANALOGUE_INPUT_PIN = 26
DECIMAL_PRECISION = 3
ADC_RANGE = float((math.pow(2, 16) - 1))
#######################################
# Global variables
#######################################
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
def read_analogue_voltage(pin):
global prev_analogue_voltage, DECIMAL_PRECISION
# Take MEASUREMENT_COUNT measurements and average them
total_value = 0
MEASUREMENT_COUNT = 16
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, DECIMAL_PRECISION)
if analogue_voltage != prev_analogue_voltage:
prev_analogue_voltage = analogue_voltage
# Temperature Reading
# When using the NTC, change the line below to
# if True
# then observe the temperature values on console.
# Note that the implementation displays the absolute value.
# So, both -24.0C and 24.0C appear as 24.0.
DECIMAL_PRECISION = 2
temp = 0
# 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')
print(f'voltage: {analogue_voltage} mV')
# Function to setup GPIO/ADC pins
def setup():
global analogue_voltage_pin
analogue_voltage_pin = machine.ADC(ANALOGUE_INPUT_PIN)
if __name__ == '__main__':
setup()
while True:
read_analogue_voltage(analogue_voltage_pin)
time.sleep(0.5)