Read the potentiometer
Section 10: Sensors and screens in codeLesson 10.1 · ⏱ 6 min
analogRead(A0) reads a number from 0 to 1023 depending on how far the potentiometer is turned. We print it to watch the numbers change.
void setup() {
Serial.begin(9600);
}
void loop() {
int v = analogRead(A0);
Serial.println(v);
delay(200);
}

🖥️ What happens on the stage?
We ran this code in Robo Maker and the challenge passed: “Bravo! It works”.
📌 Another example: the knob as a percentage
map turns 0–1023 into 0–100, so we read the percentage.
void setup() {
Serial.begin(9600);
}
void loop() {
int v = analogRead(A0);
int p = map(v, 0, 1023, 0, 100);
Serial.print(p);
Serial.println(" %");
delay(300);
}
30 %
30 %
25 %
25 %
25 %
25 %
74 %
74 %
74 %
74 %
✍️ Practise
Print v and turn the knob.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
Write “LOW” if the value is below 512, and “HIGH” if it is above.
👀 Show the solution🙈 Hide the solution
void setup() {
Serial.begin(9600);
}
void loop() {
int v = analogRead(A0);
if (v < 512) {
Serial.println("LOW");
} else {
Serial.println("HIGH");
}
delay(300);
}
LOW
LOW
LOW
LOW
LOW
LOW
HIGH
HIGH
HIGH
HIGH
Result: LOW, then HIGH.
Medium
Write the value in volts: v × 5 ÷ 1023.
👀 Show the solution🙈 Hide the solution
void setup() {
Serial.begin(9600);
}
void loop() {
int v = analogRead(A0);
float volts = v * 5.0 / 1023;
Serial.print(volts);
Serial.println(" V");
delay(300);
}
1.50 V
1.50 V
2.50 V
2.50 V
2.50 V
2.50 V
2.50 V
2.50 V
2.50 V
Result: like 2.50 V halfway.
Hard
Write three words by position: “left” below 341, “middle” below 682, otherwise “right”.
👀 Show the solution🙈 Hide the solution
void setup() {
Serial.begin(9600);
}
void loop() {
int v = analogRead(A0);
if (v < 341) {
Serial.println("left");
} else if (v < 682) {
Serial.println("middle");
} else {
Serial.println("right");
}
delay(300);
}
left
left
left
left
left
left
middle
middle
middle
middle
right
right
Result: left, then middle, then right.

