Sub topic 7
Reading the Potentiometer with analogRead()
This chapter assumes you can upload a sketch, open the Serial Monitor, and wire a breadboard. It also assumes you know what the ADC and reference voltage are from earlier chapters. The potentiometer is already wired as a voltage divider: one outer leg to 5 V, the other outer leg to GND, and the wiper (middle leg) to A0. Here we focus on analogRead(): what it returns, what it does internally, and the mistakes people commonly make with it.
What analogRead() does
analogRead(pin) measures the voltage on an analog input pin and returns an integer. On an Arduino Uno (ATmega328P) the ADC has 10 bits, so the result runs from 0 to 1023. The ADC compares the pin voltage to the reference voltage. By default on the Uno that reference is the 5 V supply.
int raw = analogRead(A0);The relationship is:
- 0 V on the pin returns 0.
- 5 V on the pin returns 1023.
- Voltages in between return a proportional value.
Each step is about 5 V / 1023 ≈ 4.89 mV on a 5 V Uno. The function takes a single argument and returns an int. It does not configure anything for you, so pinMode() is not required for analog input.
Pin naming
You can pass the pin in two ways:
A0is the constant for analog input 0. This is the clearest form.0also works for analog channel 0 inanalogRead(), because the function accepts channel numbers as well as pin numbers.
Prefer A0. Digital pin numbers and analog channel numbers overlap in confusing ways on some boards, and A0 avoids that.
The first sketch
This sketch reads the potentiometer on A0, converts the value to volts, and prints both.
const int POT_PIN = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int raw = analogRead(POT_PIN);
float volts = raw * (5.0 / 1023.0);
Serial.print("raw=");
Serial.print(raw);
Serial.print(" volts=");
Serial.println(volts, 2);
delay(100);
}A few points about this code:
POT_PINis aconst int, so the compiler can treat it as a fixed value and you change the pin in one place.rawis anint. On an Uno anintis 16 bits and holds 0 to 1023 without trouble.5.0 / 1023.0uses floating-point literals. If you wrote5 / 1023, integer division would produce 0 and every voltage would print as 0.00.Serial.println(volts, 2)prints two decimal places.delay(100)limits output to about ten lines per second so the Serial Monitor stays readable.
Open the Serial Monitor at 9600 baud and turn the knob. The output should sweep from near raw=0 volts=0.00 to near raw=1023 volts=5.00.
What happens inside the call
On AVR boards such as the Uno, analogRead() does these steps:
- It selects the requested channel on a multiplexer that feeds a single ADC.
- It starts a conversion.
- It waits for the conversion to finish.
- It returns the result.
Three consequences follow.
The call blocks. The ADC clock is the CPU clock divided by 128, which gives 125 kHz on a 16 MHz Uno. One conversion takes about 13 ADC clock cycles, so roughly 104 microseconds. The practical maximum is near 9,600 readings per second. This is fast compared with delay(100), but it matters if you read many channels in a tight loop.
There is one ADC. All analog pins share it through the multiplexer. After you switch channels, the sample-and-hold capacitor may still carry charge from the previous pin. If the previous pin had a very different voltage, the first reading on the new pin can be slightly off. This effect grows when the source resistance is high. The potentiometer's wiper impedance is low enough with typical 10 kΩ parts, but it is the reason for the advice in the next section.
The reading is a snapshot. The value reflects the voltage at the moment of sampling, not an average over time. That is why raw readings jitter, which later chapters address.
Source impedance and the 10 kΩ guideline
The ATmega328P datasheet recommends that the signal source have an output impedance of about 10 kΩ or less. A potentiometer's wiper resistance seen by the ADC varies with the knob position. At the midpoint of a 10 kΩ pot, the source resistance is about 2.5 kΩ (the two halves in parallel). That is within the guideline.
If you use a 100 kΩ pot, the midpoint source resistance rises to about 25 kΩ. Readings become noisier and can lag behind fast knob movements. Use 10 kΩ pots for this circuit unless you have a reason not to.
Common errors
The following table lists the mistakes that cause most problems when reading a potentiometer.
| Symptom | Likely cause | Fix |
|---|---|---|
| Reading is always 0 | Wiper not connected, or the pot is wired so A0 sits at GND | Check that the middle leg goes to A0 and the outer legs go to 5 V and GND |
| Reading is always 1023 | A0 tied to 5 V, or the wiper wire is in the wrong breadboard row | Move the wire to the middle leg's row |
| Reading wanders when the knob is untouched | Wiper wire is loose, or the pin is floating | Reseat the wire. An unconnected analog pin reads random values |
| Range is only about 0 to 512 | Outer leg wired to 3.3 V, or only half of the track is used | Wire the outer legs to 5 V and GND |
| Voltage always prints as 0.00 | Integer division in the conversion | Use `5.0 / 1023.0` |
| Reading goes backward | Outer legs are swapped | Swap the 5 V and GND legs, or invert in code |
| Values jump when you touch the knob's metal shaft | Hand capacitance and mains noise | Use a plastic knob, or smooth the value in software |
Floating pins
An analog pin with nothing connected is called floating. Its voltage is set by stray charge and nearby signals, so analogRead() returns drifting values. This is a useful diagnostic: if the value changes when you wave your hand near the pin, the wiper is not making contact. It is not a feature to rely on. In particular, do not use floating-pin readings as a random seed in anything that matters.
Using the reading without float math
The volts conversion above uses floating point, which is fine on an Uno for occasional use but slower and larger than integer math. When you only need millivolts, use integers and multiply before you divide:
const int POT_PIN = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int raw = analogRead(POT_PIN);
long millivolts = (long)raw * 5000L / 1023L;
Serial.print("raw=");
Serial.print(raw);
Serial.print(" mV=");
Serial.println(millivolts);
delay(100);
}The cast to long matters. raw * 5000 can reach 5,115,000, which overflows a 16-bit int (maximum 32,767) on an Uno. Without the cast the result wraps to a wrong value. Multiplying first keeps precision, because dividing raw / 1023 first would give 0 for every reading below 1023.
Using the reading to drive an output
The raw value is rarely the final number you need. A common next step is to scale it with map() and send it to a PWM pin:
const int POT_PIN = A0;
const int LED_PIN = 9;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
int raw = analogRead(POT_PIN);
int brightness = map(raw, 0, 1023, 0, 255);
analogWrite(LED_PIN, brightness);
}The potentiometer now dims the LED on pin 9. Later chapters cover map() and PWM in detail. For this chapter, note that analogRead() returns 0 to 1023 while analogWrite() expects 0 to 255. Passing the raw value straight to analogWrite() would wrap around and produce flickering, wrong brightness.
Timing and reading cadence
Reading in loop() without any delay is legal. The loop then runs as fast as the conversion allows, at roughly several thousand iterations per second. This is useful for responsive control but floods the Serial Monitor if you print every time. Three approaches are common:
- Add a
delay()of tens of milliseconds, which is simple but blocks the rest of the sketch. - Read every pass but print only on a timer using
millis(). - Print only when the value changes meaningfully, which is the deadband approach covered later.
Checklist for a reliable reading
- Use a 10 kΩ potentiometer with the outer legs on 5 V and GND.
- Connect the wiper to an analog pin and reference it as
A0, not a bare number. - Store the raw result in an
int, not abyte, since 1023 does not fit in 8 bits. - Use floating-point literals or
longcasts when converting. - Confirm the full 0 to 1023 range by turning the knob to both ends before building on the value.
Exercise
A sketch contains float volts = raw * (5 / 1023); and always prints 0.00 even though raw changes from 0 to 1023. Why, and what is the fix?
Show answer
In 5 / 1023 both operands are integers, so C++ uses integer division, which gives 0. Multiplying raw by 0 gives 0. Change it to 5.0 / 1023.0 so the division uses floating point, as in float volts = raw * (5.0 / 1023.0);.
Exercise
You compute millivolts with int mv = raw * 5000 / 1023; on an Uno and the values are wrong for readings above about 6. What causes this, and how do you correct it?
Show answer
On an Uno an int is 16 bits with a maximum of 32,767. The product raw * 5000 exceeds that once raw is above 6, so it overflows before the division. Cast to long and use long constants: long mv = (long)raw * 5000L / 1023L;.
Exercise
With the knob untouched, the raw value drifts between 400 and 700. Name two likely causes and one way to check.
Show answer
The wiper wire may be loose or in the wrong breadboard row, leaving A0 floating, or the outer legs may not be firmly connected to 5 V and GND. To check, disconnect the wiper from A0 and see whether the value wanders when you wave your hand near the pin. If it does, the pin was floating, so reseat the wiper connection.