from machine import ADC, Pin, PWM
from time import sleep
adc = ADC(Pin(36)) # create ADC object on ADC pin
adc.read() # read value, 0-4095 across voltage range 0.0v - 1.0v
adc.atten(ADC.ATTN_11DB) # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v)
adc.width(ADC.WIDTH_10BIT) # set 9 bit return values (returned range 0-1023
def map_analog_to_PWM(value, leftMin, leftMax, rightMin, rightMax):
# Figure out how 'wide' each range is
leftSpan = leftMax - leftMin
rightSpan = rightMax - rightMin
# Convert the left range into a 0-1 range (float)
valueScaled = float(value - leftMin) / float(leftSpan)
# Convert the 0-1 range into a value in the right range.
return int(rightMin + (valueScaled * rightSpan))
pwm = PWM(Pin(2), freq=50, duty=0) # create and configure in one go
while True:
analog_in = adc.read()
duty=map_analog_to_PWM(analog_in, 0, 1023, 0, 100)
print(analog_in) # read value using the newly configured attenuation and width
print(duty)
print("")
pwm.duty(duty)
sleep(0.1)