Read the code

Here is the whole sketch. It reads the knob and sends the number to your computer7.

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);
}

You met // notes, setup and loop in Lesson 1.

What each line does

  1. Serial.begin(115200);Starts the serial link to the computer, at 115200 baud8.
  2. int reading = analogRead(A0);Reads the voltage on pin A0 as a number1. Stores it in a variable called reading10.
  3. Serial.println(reading);Sends that number as text, then starts a new line9.
  4. delay(20);Waits 20 milliseconds11. Then loop runs again and reads the knob once more5.

Why the top is 1023

The board splits 0 to 5 volts into 1024 small steps1. Counting starts at 0, so the steps are 0 to 1023.

Each step is about 0.0049 volts1.

Sources for this page

  1. Arduino reference: analogRead
  2. Arduino example: AnalogReadSerial: potentiometer wiring
  3. Arduino tutorial: Analog Read Serial: what a potentiometer does; 0 V reads 0 and 5 V reads 1023
  4. Arduino reference: Serial.begin()
  5. Arduino reference: Serial.println()
  6. Arduino reference: int
  7. Arduino reference: delay