This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Flick the switch [Dec. 18, 2011, 8:26 p.m.]



In the previous two tasks, you built a simple circuit and learned about the two main functions of an Arduino program: setup(){ ... } and loop(){ ... }

Now these two sides, hardware and software, can be put together. Let's start with what should happen at the beginning of your program, in the setup function.

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

This sets pin 3 (the digital pin labeled 3 on your Arduino) to be an output pin, as should all LED-powering pins.  Sensors, switches, and other devices which you read from would be declared as INPUT pins.

Then recall our "if Arduino could understand English" program:

void loop(){
    Turn on the red light
    Wait one second
    Turn off the red light
    Wait one second
}

This is how it should be written in the Arduino's programming language:

void loop(){
    digitalWrite(3, HIGH); 
  delay(1000);

    digitalWrite(3, LOW);
  delay(1000); 
}

Notice a few things about the program:

* We use HIGH and LOW to send 5V or ground voltage to the LED.  Only one of these (HIGH, in our case) will light the LED.

* The delay command is given a time of 1000 milliseconds

* Each command ends with a semicolon and a new line.

* We use the number of the pin (3) and not any defining characteristics (like whether the light is red or blue)

To make programs more readable for others (and for ourselves, so we remember what each part of the code is doing), we often include comments.  Writing text in the middle of a program could confuse the computer, so we begin comments with two slashes.



void loop(){
   // turn on the red LED (pin 3) for 1 second 
    digitalWrite(3, HIGH); 
  delay(1000);

 // turn off the red LED (pin 3) for 1 second

    digitalWrite(3, LOW);
  delay(1000); 
}

For comments that can cover multiple lines, you can start with a /* and end with a */.

/* only a comment */

/*  My Program
   by me
turns the red LED on and off */

/*
  Inside a comment

*/  Outside a comment!!!