import time
from machine import Pin, ADC
# output LED
led = Pin(7, Pin.OUT)
# define pot
pot_pin = 28
pot = ADC(pot_pin)
# set maximum desired flashing frequency
max_frequency = 100
# helper function to simulate arduino map() function
# maps analog input value to a set range
def analog_map(value, in_min, in_max, out_min, out_max):
return int((value - in_min) * (out_max - out_min) / (in_max - in_min)) + out_min
while True:
# read the pot
pot_value = pot.read_u16()
# calculate voltage and pot percentage (% of full range) - we assume clean and stable 3.3 V here!
volt = round((3.3/65535)*pot_value,2)
percent = int(pot_value/65535*100)
# info on pot position
print("Volt: "+str(volt)+" | Read value: "+str(pot_value)+" | percent: "+str(percent)+"%")
# get the desired flashing frequency
frequency = analog_map(pot_value, 0, 65535, 0, max_frequency)
print(frequency)
# to avoid divide by zero errors, set frequency to 1 Hz as lowest possible value if pot = 0
if frequency == 0:
frequency = 1
# calculate pulse period from frequency
period = (1 / frequency)
# duty cycle 50% => set off and on time to half period each
# could be changed to other values for different duty cycles
ton = int(round((period / 2)*1000, 0))
toff = int(round((period / 2)*1000, 0))
print(ton, '// ', toff)
# toggle the LED on and off with the sleep time set to off an on times
led.on()
time.sleep_ms(ton)
led.off()
time.sleep_ms(toff)