By

Arduino Learning #1: setup() & loop()

In Arduino programming there are two important fundamentals, the setup() function and the loop() function.

A function in programming is just like a function in math. You put in a variable, such as x, and you get a return value. In the case of setup() and loop(), the Arduino runs those functions as a way of letting the programmer (that's you) control what it does.

Side note

You can leave "comments" in code, which are just notes. Any line beginning with //, or code in between /* */ is a comment. They have no effect on the computer whatsoever, they are just for leaving messages in your code in the event that another programmer looks at what you wrote. This happens more often than you'd think.

// This is a comment

/*
 * This
 * is a multiple line
 * comment
*/

The setup() function will contain the code that you only want to run once, at the beginning of the program’s life.

Example

// Below, we must define the method setup() so that the Arduino knows what to do.
void setup() {
    int currentAge = 17; // Integer currentAge is now equal to 17
}

The loop() method will contain code that will be run over and over again by the Arduino. The Arduino will go down every line of the loop method, evaluate each line, and repeat as long as the program is running. We can use the loop method to read inputs and send outputs in real time.

Example

void loop() {

    currentAge += 1; // Increase current age by 1

    // Wait 60000 milliseconds before going on to the next line of code
    delay(60000);
}

Analogies

Here are 2 loosely “real world” concept examples of setup() and loop().

  1. In the setup() function of the iPhone, you will probably find the code that loads the background image, puts the apps on the homescreen, and does anything that is setting-related (setup). In the loop() function, you will find the code that listens for touches, swipes, and redraws the graphics on the screen.

  2. Pretend you’re playing a video game for a second, the loop method would be responsible for updating the position and orientation of the main character, and all of the other on-screen elements.

  3. Now imagine you’re on Facebook. The setup method loads the page, and the initial content, while the loop method checks for new content and loads it into the page.

The basic idea here is that setup runs once, and determines the initial conditions, whereas loop runs over and over again, and is responsible for handling and responding to new events.

This is the documentation for Arduino, it provides a complete reference of http://arduino.cc/en/Reference/HomePage

Written by
Programmer, Entrepreneur, Startup Enthusiast