1C: Our first program – “Blink.ino”


Computers are only as smart as the software…consequently; software is only as smart as the programmer who develops it.

 

The basic structure of a sketch:

void setup(){
  // Initialize anything in here first
}

void loop(){
  // The main routine where all things happen
  // Runs and loops as long as power is supplied to the Arduino
  // Power is supplied from the USB or power connector
}

void setup() – This is where all initialization happens in the Arduino

void loop() – The main routine where everything happens. It runs and loops as long as power is supplied to the Arduino. Power can be supplied through the USB or Power connector.

{ } – “curly”brackets or parenthesis. Used for showing the start and end points of control structures or blocks of programming code.

Blink.ino

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

void loop()
{
 digitalWrite(10, HIGH);
 delay(1000);
 digitalWrite(10, LOW);
 delay(1000);
}

 

pinMode(10, OUTPUT) – Tells the Arduino how the pin is used

OUTPUT – constant that defines the pin as an output device

INPUT – constant that defines the pin will expect input from a sensor or circuit

; - used to end a statement

 

digitalWrite(10, HIGH) – Sets the indicated pin to HIGH

HIGH – Set power on

LOW – Set power off

delay(1000) – Tells the program to pause for a given number of milliseconds


 

Programming Style and Commenting

  • // - Comments. Anything after these double slashes are ignored by the compiler\
  • /* */ - Comments. Anything between the start (/*) and end (*/) comments are ignored by the compiler. This allows programmers to block out a section of code easily by spanning multiple lines.
  • Indenting
  • Use of white space (extra lines, extra spaces, etc.)

 

Blink.ino – Second try, but with proper comments

/*
* BLINK
* =====
*
* Filename: blink.ino
*
* Description:
* This program turns on and off an LED with a delay in milliseconds
*
* Inputs: none
* Outputs: LED light
*
* Author: D. Lee
* Created: June 2014
*
* Revisions:
*/

// Setup and initialize the program
void setup()
{
pinMode(10, OUTPUT); // Initialize pin 10 as an output device
}

// Main routine that runs (loops as longs as power is available)
void loop()
{
digitalWrite(10, HIGH); // turn LED on
delay(1000); // delay for 1000 ms (1 sec)
digitalWrite(10, LOW); // turn LED off
delay(1000); // delay for 1000 ms (1 sec)
}

 

 

Notice the comments and indents.

It makes the code a lot more readable.


Additional reference material can be found at the Arduino website - http://arduino.cc/en/Reference/HomePage