from machine import Pin, ADC,PWM,Timer
from time import sleep
adc = ADC(Pin(34))
adc.atten(ADC.ATTN_11DB) # sets for a maximum input voltage of 3.6 volts
adc.width(ADC.WIDTH_9BIT) # sets the bit width to 12 bits
pwm0 = PWM(Pin(21))
pwm0.freq(50)
tim0 = Timer(0)
pwm0.duty(25)
switch =0
step=25
val = 0
def handler_0(tim0):
global val
global step
if step < 125:
pwm0.duty(step)
step=step+1
val=step
elif step > 124:
pwm0.duty(val)
val=val-1
if val < 26:
step=val
while True:
adc_value = adc.read()
volts = (3.3*adc_value)/511
if 0 <= volts <= 0.5:
pwm0.duty(25)
switch = 0
tim0.deinit()
elif 0.5 <= volts <= 1:
pwm0.duty(50)
switch = 0
tim0.deinit()
elif 1 <= volts <= 1.5:
pwm0.duty(75)
switch = 0
tim0.deinit()
elif 1.5 <= volts <= 2:
pwm0.duty(100)
switch = 0
tim0.deinit()
elif 2 <= volts <= 2.5:
pwm0.duty(125)
switch = 0
tim0.deinit()
else:
if switch == 0:
switch = 1
tim0 = Timer(0)
tim0.init(period=100, mode=Timer.PERIODIC, callback=handler_0)
input_voltage = "The input voltage is {:0.3f} volts and raw value is {:4d}"
print(input_voltage .format(volts,adc_value,switch),end = "\r")