First of all, let's do the hardware connection.
We need to connect the potentiometer to the Arduino ADC. We can use any of the potentiometers with values between 1kΩ and 10kΩ.
Similarly, we can connect the LED properly to any one of the PWM pins.
Considering LED drop voltage of ~2 volts and 10mA current, we can use a Resistor with a value
R = (Vcc - Vled) / I
= (5-2)/0.01
= 300 Ω
Let’s understand the brightness mapping.
Since ADC will provide us the value from 0 to 1023
Similarly, we have to control LED brightness using PWM by providing values from 0 to 255
So we need to map the ADC value to the PWM brightness value.
We can do it by default function map();
We can provide the ADC and PWM ranges, so this function returns the proper mapping value accordingly.
// potentiometer is connected to an A0 pin
// LED is connected to pin no.9
void setup() {
pinMode(9, OUTPUT); // Set the LED pin as an output
}
void loop() {
int adcValue = analogRead(A0); // Read the analog value from pin A0 (range: 0–1023)
// Read the potentiometer value (0-1023) and map it to the PWM range (0-255)
int brightness = map(adcValue, 0, 1023, 0, 255);
// Adjust the LED brightness
analogWrite(9, brightness);
}
So, the above code simply maps the ADC value to the expected PWM value by using the following map function.
int brightness = map(analogRead(potPin), 0, 1023, 0, 255);
So as we can see, in the above map function, we have passed a total of 5 parameters, from which the ADC_value will be converted from Range (0-1023) to (0-255)
We can calculate the mapping factor,
Mapping Factor = ADC Value / corresponding PWM value
= 1024 / 256
= 4
So whatever ADC value we receive, dividing it by 4 will give us the corresponding PWM value.
// Potentiometer is connected to A0 pin (analog input)
// LED is connected to pin no. 9 (PWM output)
void setup() {
pinMode(9, OUTPUT); // Configure pin 9 as an output to control the LED
}
void loop() {
// Read the analog value from pin A0 (range: 0–1023)
// The potentiometer adjusts this value based on its position
int adcValue = analogRead(A0);
// Map the potentiometer value (0–1023) to the PWM range (0–255)
// Dividing by 4 is equivalent to the mapping (1024 / 256 = 4)
int brightness = adcValue / 4;
// Write the mapped brightness value to the LED
// This controls the LED brightness proportionally to the potentiometer position
analogWrite(9, brightness);
}