1.5 Code Blink

[code lang="arduino" firstline="1"]
/*
Blink
Turns on an LED on for one second,
then off for one second, repeatedly.

This example code is in the public domain.
*/

void setup() {
// initialize the digital pin as an output.
// Pin 13 has an LED connected on most Arduino boards:
pinMode(13, OUTPUT);
}

void loop() {
digitalWrite(13, HIGH); // set the LED on
delay(1000); // wait for a second
digitalWrite(13, LOW); // set the LED off
delay(1000); // wait for a second
}
[/code]

Here is the example Arduino blink code. We call the programs we write for Arduino “sketches.” The Arduino program comes with many basic example sketches available in the file menu. Lets take a look at what is happening in this sketch.

The text in grey are called comments. It is a good idea to comment your code as you write it. This is just to make the code easier for people to read. All text that appears in between /* and */ or after // becomes a comment. The computer strips out the comments when uploading the program to the Arduino.

Here is the same code without the comments:

[code lang="arduino" firstline="8" gutter="0"]
void setup() {
pinMode(13, OUTPUT);
}

void loop() {
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
[/code]

If you are new to code this can seem very confusing but don’t worry. Once you learn it, it’s cake. In this sketch we can see there are two sections. The setup and the loop section. Sections of code like this are called functions. Each function is a collection of commands. We call the individual commands statements. Each command always ends with the “;” character.

Every Arduino sketch will contain at least these two functions. The Arduino reads each line of code from top to bottom just as we do. The “setup” function is where we can change various settings of the Arduino. The setup function is read when the sketch first runs on the Arduino. The “loop” function is read next and when all of the statements in the loop function are read, the loop function begins again.

We will look at the individual statements in the next section.


Recap

  • We create sketches to load onto the Arduino.
  • A sketch contains sections of code called functions.
  • Each function contains individual Arduino commands called statements.
  • The setup function runs once and the loop function runs again and again.

Leave a Reply