انتقل للمحتوى
Robo EgyptRobo Egypt
☰ Course contents
Robo Maker: home
0. Lab tour1
1. The start: the Arduino6
2. Wiring and the traffic light4
3. Inputs: the button4
4. Sound and movement5
5. Sensors and numbers5
6. Distance, the screen and colours5
7. Motors and the car4
8. The project: the city's smart gate3
9. From blocks to C++ code5
10. Sensors and screens in code5
11. Smart systems5
12. Bluetooth: control from the phone1

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.

⚙️ Print the value of A0
void setup() {
  Serial.begin(9600);
}

void loop() {
  int v = analogRead(A0);
  Serial.println(v);
  delay(200);
}
We turned the knob and the numbers changed
We turned the knob and the numbers changed
🖥️ 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.

⚙️ The knob as a 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);
}
🖥️ Serial Monitor
30 %
30 %
25 %
25 %
25 %
25 %
74 %
74 %
74 %
74 %
✍️ Practise
Print v and turn the knob.
✍️ Practise here in the lessonor 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
⚙️ Solution
void setup() {
  Serial.begin(9600);
}

void loop() {
  int v = analogRead(A0);
  if (v < 512) {
    Serial.println("LOW");
  } else {
    Serial.println("HIGH");
  }
  delay(300);
}
🖥️ Serial Monitor
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
⚙️ 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);
}
🖥️ Serial Monitor
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
⚙️ 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);
}
🖥️ Serial Monitor
left
left
left
left
left
left
middle
middle
middle
middle
right
right

Result: left, then middle, then right.

Finished the lesson? Mark it so your progress counts.