انتقل للمحتوى
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

Your first real code

Section 9: From blocks to C++ codeLesson 9.1 · ⏱ 7 min

Engineers program the Arduino in C++. The same ideas as the blocks, but written: setup runs once, and loop repeats. In Robo Maker, click ⌨ C++ code to type, or “Get the blocks’ code” to see your blocks' code.

⚙️ The LED on pin 13 lights up
void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);
}

void loop() {
}
  • pinMode(13, OUTPUT); pin 13 sends electricity out.
  • digitalWrite(13, HIGH); turn it on.
  • Every line ends with ;, and capital and small letters matter.
The code in Robo Maker, and the LED on
The code in Robo Maker, and the LED on

📌 Another example: on, then off

In setup: turn pin 13 on, wait two seconds, then turn it off.

⚙️ On, then off
void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);
  delay(2000);
  digitalWrite(13, LOW);
}

void loop() {
}
The first two seconds: on
The first two seconds: on
After them: off
After them: off
✍️ Practise
Run the solved example.
✍️ Practise here in the lessonor open the lab in a new page ↗
✍️ Practise
Write the line that turns it on yourself.
✍️ Practise here in the lessonor open the lab in a new page ↗

🎯 Challenge yourself

Easy

Write the code that turns the LED on 13 off.

👀 Show the solution
⚙️ Solution
void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() {
}
In the lab
In the lab

Result: the LED is off.

Medium

Two LEDs on 13 and 12: turn them on together.

👀 Show the solution
⚙️ Solution
void setup() {
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  digitalWrite(13, HIGH);
  digitalWrite(12, HIGH);
}

void loop() {
}
In the lab
In the lab

Result: they light up together.

Hard

The code has a mistake: digitalwrite(13, HIGH). Fix it, then run it.

👀 Show the solution
⚙️ Solution
void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);
}

void loop() {
}
In the lab
In the lab

Result: the W is a capital: digitalWrite.

Finished the lesson? Mark it so your progress counts.