Combine ADC and PWM: read a potentiometer’s position and use it to control an LED’s brightness, so turning the knob smoothly dims or brightens the light.


Connections:

Disconnect all power before building the circuit. Reconnect once verified.
File: 02_input_and_output/code/Soft_LED.py
from machine import Pin,PWM,ADC
import time
pwm =PWM(Pin(14,Pin.OUT),1000)
adc=ADC(Pin(1))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)
def remap(value,oldMin,oldMax,newMin,newMax):
return int((value)*(newMax-newMin)/(oldMax-oldMin))
try:
while True:
adcValue=adc.read()
pwmValue=remap(adcValue,0,4095,0,1023)
pwm.duty(pwmValue)
print(adcValue,pwmValue)
time.sleep_ms(100)
except:
adc.deinit()
pwm.deinit()
02_input_and_output/code/.Soft_LED.py.pwm =PWM(Pin(14,Pin.OUT),1000)
adc=ADC(Pin(1))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)
PWM on GPIO14 drives the LED; the ADC on GPIO1 reads the potentiometer, same as in Read the Voltage of a Potentiometer.
def remap(value,oldMin,oldMax,newMin,newMax):
return int((value)*(newMax-newMin)/(oldMax-oldMin))
The ADC produces values from 0–4095, but pwm.duty() only accepts 0–1023. remap() rescales a value from one range (oldMin–oldMax) proportionally into another (newMin–newMax).
while True:
adcValue=adc.read()
pwmValue=remap(adcValue,0,4095,0,1023)
pwm.duty(pwmValue)
print(adcValue,pwmValue)
time.sleep_ms(100)
Reads the raw ADC value, remaps it from the ADC’s 0–4095 range into PWM’s 0–1023 range, and writes it straight to the LED’s duty cycle.
remap() is a general-purpose pattern for converting any value from one numeric scale to another — useful whenever an input range doesn’t match an output rangeSee Class ADC and Class PWM(pin, freq) for the full API reference.
remap()-based brightness curve that feels more linear to the eye (human brightness perception isn’t linear).freq() to make a “Theremin”-style pitch control.Adapted from Python_Tutorial.pdf Project 10.1