Skip to content
RoboLearn
Not completed

Arduino C++ basics

ProgrammingBeginner40 minCode along in the simulator ↓Before this: Arduino UNO

What you’ll learn

  • The shape of every Arduino program (a sketch)
  • How to switch pins on and off and read them
  • Variables, if statements and printing messages with Serial

Every sketch has two parts

void setup() {
// Runs ONCE when the board powers on or resets
}
void loop() {
// Runs AGAIN and AGAIN, forever
}

This is the sense, think, act loop in code: loop() is where your robot senses, decides and acts, thousands of times per second.

const int LED = 13; // a name for pin 13 (the built-in LED)
void setup() {
pinMode(LED, OUTPUT); // pin 13 will SEND signals out
}
void loop() {
digitalWrite(LED, HIGH); // turn the pin ON (5 V)
delay(1000); // wait 1000 milliseconds = 1 second
digitalWrite(LED, LOW); // turn the pin OFF (0 V)
delay(1000);
}
Code Meaning
const int LED = 13; Make a named number. const means it never changes
pinMode(pin, OUTPUT) Set a pin to send signals (LEDs, buzzers)
pinMode(pin, INPUT_PULLUP) Set a pin to read a button (more below)
digitalWrite(pin, HIGH/LOW) Turn an output pin on or off
digitalRead(pin) Read an input pin: gives HIGH or LOW
delay(ms) Pause for that many milliseconds

Grammar rules (syntax)

C++ is fussy. Most beginner errors are one of these:

  • Every statement ends with a semicolon ;
  • Code blocks live inside curly braces { }, and every { needs a matching }
  • Names are case-sensitive: digitalWrite works, DigitalWrite doesn’t
  • // starts a comment, a note for humans that the board ignores

Variables

A variable is a named box that holds a value that can change.

int count = 0; // whole numbers
float distance = 12.5; // numbers with decimals
bool pressed = false; // true or false

Making decisions with if

if (pressed) {
digitalWrite(LED, HIGH);
} else {
digitalWrite(LED, LOW);
}

Compare with == (equal), != (not equal), <, >, <=, >=. Remember: = stores a value, == compares two values.

Talking to your computer: Serial

Serial lets the board send text to the IDE’s Serial Monitor (magnifying-glass icon, top right). It’s your number-one debugging tool.

int count = 0;
void setup() {
Serial.begin(9600); // start talking at 9600 bits per second
}
void loop() {
Serial.print("Count: ");
Serial.println(count); // println adds a new line
count = count + 1;
delay(500);
}

Set the Serial Monitor’s speed to 9600 baud to match, or you’ll see gibberish.

Finished this lesson?