Look below the sketch
You can skip this page. It shows what analogRead does inside the chip.
The chip has an ADC, a part that turns a voltage into a number7. Small memory slots called registers control it.
analogRead(A0) starts one conversion on A0 and waits until it finishes3.
The four registers
- ADMUX picks the reference and the input. Its bits REFS1:0 = 01 pick AVCC. MUX3:0 = 0000 picks input ADC02.
- ADCSRA runs the ADC. ADEN turns it on. ADPS2:0 = 111 divides its clock by 1282.
- Writing 1 to ADSC starts a conversion3. ADSC reads as 1 until the conversion finishes2.
- ADCL and ADCH hold the result, ADC = VIN × 1024 / VREF. Read ADCL first, then ADCH2.
The same reading, two ways
l2-read-arduino.ino// Lesson 2, Arduino version: read the knob on A0 and
// print the reading.
void setup() {
Serial.begin(115200);
}
void loop() {
int reading = analogRead(A0); // 0 to 1023 on the UNO R3
Serial.println(reading);
delay(20);
}l2-read-registers.ino// Lesson 2, register version: the same reading, done with
// the ADC registers.
void setup() {
Serial.begin(115200);
// Reference AVCC, input ADC0 (A0), result right-adjusted
ADMUX = (1 << REFS0);
// Turn the ADC on, with its clock at 16 MHz / 128
ADCSRA = (1 << ADEN)
| (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
}
void loop() {
ADCSRA |= (1 << ADSC); // start one conversion
while (ADCSRA & (1 << ADSC)) {} // ADSC stays 1 until done
uint8_t low = ADCL; // read ADCL first
uint8_t high = ADCH;
int reading = (high << 8) | low;
Serial.println(reading);
delay(20);
}Registers in this lesson (ATmega328P data-space addresses)2
| Register | Address | Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0 |
|---|---|---|---|---|---|---|---|---|---|
| ADMUX | 0x7C | REFS1 | REFS0 | ADLAR | – | MUX3 | MUX2 | MUX1 | MUX0 |
| ADCSRA | 0x7A | ADEN | ADSC | ADATE | ADIF | ADIE | ADPS2 | ADPS1 | ADPS0 |
| ADCH | 0x79 | – | – | – | – | – | – | ADC9 | ADC8 |
| ADCL | 0x78 | ADC7 | ADC6 | ADC5 | ADC4 | ADC3 | ADC2 | ADC1 | ADC0 |
Watch the registers
Switch between the two programs and slide the knob. Watch ADCH and ADCL change. At 2.5 V both programs print 5122.
Sources for this page
- Arduino reference: analogRead
- Microchip ATmega328P datasheet DS40002061A: §24.7 ADC conversion result (p256); Table 24-3 (p257); ADEN and ADSC (p258)
- ArduinoCore-avr, cores/arduino/wiring_analog.c
- Arduino tutorial: Analog Read Serial: what a potentiometer does; 0 V reads 0 and 5 V reads 1023