Roborear

Arduino Button, LED & Potentiometer: Every Line of Code Explained (Robotics Course Ep 2) · Lesson 2 of 2

Arduino Button, LED & Potentiometer: Every Line of Code Explained (Robotics Course Ep 2)

▶ 19:01 video

Loads from YouTube when you press play, and YouTube may then set cookies. Watch on YouTube

In this episode you build three small circuits: an external LED that blinks, a push button that switches the LED on, and a knob (a potentiometer) whose value you can watch live on your screen. You also learn the rules of Arduino code, so you can read every line instead of copying it.

These are the building blocks of every robot in this course: outputs (LEDs, later motors), digital inputs (buttons, later sensors) and analog inputs (knobs, later light and distance sensors).

What you will be able to do

  • Explain what setup() and loop() do and when each one runs

  • Use curly braces, semicolons and comments correctly, and remember that Arduino code is case sensitive

  • Wire an LED with a resistor on a breadboard

  • Read a compile error, and use AI to understand it without skipping the learning

  • Use a variable like const int LED_PIN so your code is easy to change

  • Read a push button with digitalRead and INPUT_PULLUP, and decide with if/else

  • Read a potentiometer with analogRead and watch it in the Serial Monitor and Serial Plotter

What you need

  • Arduino Nano or Uno (a Nano expansion board is optional)

  • A breadboard and jumper wires

  • 1 LED and a 220 Ω resistor (330 Ω also works)

  • 1 push button

  • 1 potentiometer (any value, for example 10 kΩ)

  • A USB data cable

Episode 1 challenge: SOS in Morse code

Last time, the challenge was to blink SOS on the built-in LED. In the video I use short blinks of 200 ms and long blinks of 600 ms. Morse code for SOS is three short, three long, three short (· · · – – – · · ·), then a pause. Here it is written out line by line, using only what you learned in Episode 1:

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  // S: three short blinks
  digitalWrite(LED_BUILTIN, HIGH); delay(200); digitalWrite(LED_BUILTIN, LOW); delay(200);
  digitalWrite(LED_BUILTIN, HIGH); delay(200); digitalWrite(LED_BUILTIN, LOW); delay(200);
  digitalWrite(LED_BUILTIN, HIGH); delay(200); digitalWrite(LED_BUILTIN, LOW); delay(200);

  // O: three long blinks
  digitalWrite(LED_BUILTIN, HIGH); delay(600); digitalWrite(LED_BUILTIN, LOW); delay(200);
  digitalWrite(LED_BUILTIN, HIGH); delay(600); digitalWrite(LED_BUILTIN, LOW); delay(200);
  digitalWrite(LED_BUILTIN, HIGH); delay(600); digitalWrite(LED_BUILTIN, LOW); delay(200);

  // S: three short blinks
  digitalWrite(LED_BUILTIN, HIGH); delay(200); digitalWrite(LED_BUILTIN, LOW); delay(200);
  digitalWrite(LED_BUILTIN, HIGH); delay(200); digitalWrite(LED_BUILTIN, LOW); delay(200);
  digitalWrite(LED_BUILTIN, HIGH); delay(200); digitalWrite(LED_BUILTIN, LOW); delay(200);

  delay(1000);   // pause before repeating
}

It works, but it’s long and repetitive. In Episode 3 you’ll learn loops and functions, which shrink this to a few lines. If you already solved it with a loop, well done.

The rules of Arduino code

Open a new sketch (File → New Sketch). Before writing anything, look at the two parts every sketch has:

void setup() {
  // runs ONCE, when the board powers on or you press reset
}

void loop() {
  // runs AGAIN AND AGAIN, top to bottom, forever
}
RuleWhat it means
Curly braces { }Everything between a pair belongs to that function (setup or loop). Every { needs its }.
Semicolon ;Ends each instruction, like a full stop ends a sentence. Lines that open or close braces don’t need one.
Case sensitivedigitalWrite and digitalwrite are different words. Only the exact spelling works.
// commentA note for people on one line. The board ignores it.
/* comment */A note that can run over several lines.

Circuit 1: an external LED

An LED is a diode, so it only works one way round. The long leg is positive (+) and the short leg is negative (−). It also needs a resistor in series. Without one, too much current flows and the LED (or the Arduino pin) can be damaged. I use 220 Ω; 330 Ω works too and makes the LED a little dimmer. A resistor has no direction.

How a breadboard is connected inside

Diagram: each column of five holes a to e is connected, f to j is a separate group, and the power rails run along the edges
Holes in the same short group of five are connected. The centre gap separates the two halves.

Plug two legs into the same group of five holes and they are connected. Put them in different groups (or across the centre gap) and they aren’t. The long + and − rails along the edges are for power and ground. On some long breadboards the rails are split in the middle, so check yours with a multimeter.

A breadboard held over a desk with an LED and a resistor plugged into its rows
The LED and the resistor share one row, so they are connected.

Wiring

  1. Put the LED in the breadboard. Plug the resistor into the same row as the LED’s long leg.

  2. Connect the other end of the resistor to digital pin D3 with a jumper wire.

  3. Connect the LED’s short leg to GND on the Arduino.

I use a Nano on an expansion board, which has a male header for every pin. On a bare Nano or an Uno, connect jumper wires straight to the pins.

Connecting a jumper wire from the breadboard to pin D3 of an Arduino Nano expansion board
Wiring to D3 on the Nano expansion board. Any digital pin works.

The code

void setup() {
  pinMode(3, OUTPUT);          // pin 3 will send a signal out
}

void loop() {
  digitalWrite(3, HIGH);       // LED on
  delay(500);                  // wait 500 ms
  digitalWrite(3, LOW);        // LED off
  delay(500);
}

Connect the board, choose your board and port, and click Upload. The LED on the breadboard blinks twice per second. That’s your first external circuit.

Your first error, and how to use AI with it

Remove the semicolon after one delay(500) and upload again. The upload stops with a red error:

Arduino IDE showing the compilation error expected ';' before 'digitalWrite' after a missing semicolon
expected ';' before 'digitalWrite': the semicolon is missing on the line above the one it points to.

The compiler says expected ';' before 'digitalWrite'. It notices the problem at the next instruction, so the missing semicolon is on the line before the one it points to.

In this course I also show how to use AI well. Copy your code and the error message into ChatGPT (or any AI tool) and ask why it happens. It will tell you a semicolon is missing. Then make sure you understand why, so you can fix it yourself next time. AI is a great helper, but you still need to understand every line.

Variables: change a pin in one place

Our code uses the number 3 in three places. To move the LED to pin 4, you’d have to change all three, and missing one is an easy bug. A variable is a named container for a value. const means it never changes while the program runs, and int means it’s a whole number:

const int LED_PIN = 4;         // change the pin here only

void setup() {
  pinMode(LED_PIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_PIN, HIGH);
  delay(500);
  digitalWrite(LED_PIN, LOW);
  delay(500);
}

Move the LED wire from D3 to D4, upload, and it blinks again. Only one line changed. We need D3 free now, because the button goes there.

Circuit 2: a push button

A push button has no direction. Put it on the breadboard so it bridges the centre gap. Connect one side to D3 and the other side to GND. That’s all: no resistor, for a reason you’ll see in a moment.

Wiring diagram: LED and 220 ohm resistor on D4, push button between D3 and GND, potentiometer on 5V, A0 and GND
The full wiring for this episode. The knob is added in circuit 3.
Hand pressing a push button on a breadboard wired to an Arduino Nano
The button: one side to D3, the other to GND.

The goal: while you hold the button, the LED is on. Let go and it turns off.

const int LED_PIN = 4;
const int BUTTON_PIN = 3;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT_PULLUP);    // input, with the built-in pull-up resistor
}

void loop() {
  if (digitalRead(BUTTON_PIN) == LOW) { // LOW means the button is pressed
    digitalWrite(LED_PIN, HIGH);
  } else {
    digitalWrite(LED_PIN, LOW);
  }
}
Arduino IDE with pinMode INPUT_PULLUP and an if else that turns the LED on when digitalRead returns LOW
The button sketch in the Arduino IDE.

if / else: making decisions

if checks a condition. When it’s true, the code inside its braces runs; otherwise the code inside else runs. digitalRead(BUTTON_PIN) reads the pin and returns HIGH or LOW.

= is not ==. A single = assigns a value (x = 5). A double == compares two values (is x equal to 5?). Inside an if you almost always want ==.

In the video I hit two small errors here: another missing semicolon, and a missing = in const int BUTTON_PIN = 3;. Both are normal. Read the error, fix it, upload again.

Blue LED lit on a breadboard while the push button is held down
Holding the button: the LED is on.

How INPUT_PULLUP works

This part confuses most beginners, so slowly:

Diagram: with INPUT_PULLUP the pin reads HIGH through an internal resistor, and LOW when the button connects it to GND
Not pressed: the resistor holds the pin HIGH. Pressed: the button connects it to GND, so it reads LOW.
  • INPUT_PULLUP turns on a resistor inside the microcontroller that connects the pin to 5V. With the button not pressed, the pin reads HIGH.

  • Pressing the button connects the pin directly to GND. Now the pin reads LOW.

  • So in this circuit, LOW means pressed. That’s why the code checks == LOW.

  • Without a pull-up, an unconnected input pin “floats” and can read random values. The built-in pull-up saves you an extra resistor.

Circuit 3: a potentiometer and the Serial Monitor

Digital vs analog pins

A digital input only knows two states: HIGH or LOW. The analog pins (A0, A1, A2 and so on) can measure a voltage between 0 V and 5 V and turn it into a number. That’s how you read things that change smoothly, like a knob or a light sensor.

A potentiometer is a variable resistor. The two outer pins go to 5V and GND, and the middle pin, called the wiper, outputs a voltage between them as you turn the knob.

A potentiometer with jumper wires held in two hands
A potentiometer: two outer pins and the middle wiper.
  1. One outer pin to 5V.

  2. The middle pin (wiper) to A0.

  3. The other outer pin to GND.

If the values go the “wrong” way when you turn it, swap the two outer wires.

Potentiometer wired with jumper wires to 5V, A0 and GND of an Arduino Nano
Wiring the knob: 5V, A0 and GND.
void setup() {
  Serial.begin(9600);            // start talking to the computer at 9600 baud
}

void loop() {
  int knob = analogRead(A0);     // a number from 0 to 1023
  Serial.println(knob);          // print it, then start a new line
}
  • Serial.begin(9600) starts serial communication over USB. 9600 is the speed in baud (bits per second), not a refresh rate. The Serial Monitor must be set to the same speed.

  • analogRead(A0) measures the voltage on A0 and returns a number.

  • int knob stores it in a variable.

  • Serial.println(knob) sends the number to your computer, one per line. Serial.print would put them all on one line.

Upload, then open Tools → Serial Monitor and set it to 9600 baud. Turn the knob and watch the numbers change.

Arduino IDE with the analogRead sketch and the Serial Monitor printing 1022 and 1023
The Serial Monitor: the knob turned all the way to 5V reads 1023.

Why 0 to 1023?

The Nano and Uno have a 10-bit analog-to-digital converter (ADC). 10 bits give 2¹⁰ = 1024 different values, numbered 0 to 1023. 0 V reads as 0, 5 V reads as 1023, and each step is about 5 V ÷ 1024 ≈ 4.9 mV. (In the video I first said 255 and then corrected it: 1023 is right.)

Serial Plotter

Close the Serial Monitor and open Tools → Serial Plotter. It draws the same numbers as a live graph, which makes changes much easier to see.

Arduino Serial Plotter drawing the potentiometer value as a line graph
The Serial Plotter drawing the knob value live.

The Serial Monitor and Plotter are some of the best debugging tools you have. Whenever you wonder what’s happening inside your board, print it.

One note on dimming an LED: analogRead reads a voltage. To make an LED glow at half brightness you use a different function, analogWrite, on a PWM pin (marked ~ on the board). We’ll get there later in the course.

Common mistakes

  • Missing semicolon: expected ';' before … Look at the line above the one in the error.

  • = instead of ==: inside an if, compare with ==.

  • Wrong capital letters: digitalwrite isn’t digitalWrite.

  • LED the wrong way round: the long leg goes towards the pin (through the resistor), the short leg to GND.

  • Button always “pressed”: a 4-leg button has two pairs of legs that are always connected. If the LED stays on, rotate the button 90° or use two diagonal legs.

  • Serial Monitor shows garbage: the baud rate there doesn’t match Serial.begin(9600).

Your challenge

Use the potentiometer to control how fast the LED blinks. Turn the knob one way and it blinks slowly, the other way and it blinks fast. You need two things you already know: analogRead to get a number from the knob, and delay to wait. Post your code in the YouTube comments; I’ll go over the solution in the next episode.

Next: Episode 3

Episode 3 covers loops and functions, including writing your own functions. You’ll see how they turn the long SOS sketch into just a few lines.

Lesson quiz

Button, LED and potentiometer quiz

Optional quiz

10 questions · pass mark 60% · Unlimited attempts

Ten quick questions to check what you learned. It's optional, and you can try as many times as you like.

Sign in to take this quiz

Quizzes are free with a Roborear account.

Sign in to save your progress and add this course to My Courses.