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

Setup vs. loop

How do you write a program with setup and loop functions?

Now that you have built the circuit - the hardware of your project - you can move on to the software side.

Writing an Arduino program begins with writing a setup function and a loop function:

void setup() {


void loop(){


The Arduino recognizes these functions automatically.  When a function is called, it runs each line of commands inside the { } brackets from top to bottom.  The function stops running at the closing } or a return command.  The word 'void' written before the function's name means that these functions are not returning anything.

Arduino calls the setup function once when the Arduino is turned on, reset, or reprogrammed. If you have a command that should run only at the start of the program, you would put it inside the setup function's { } brackets.

Once setup is finished, the Arduino repeats the loop function over and over again.  If the Arduino understood English, you could set up a blinking light like this:

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

When this repeats, the program will turn the red light on and off, on and off.  If you left out the first waiting time, the light would be turned off immediately after the light was turned on.  If you left out the second waiting time, the loop function would be called again, and the light would be turned on immediately after the light was turned off.  Neither would give us a blinking light.


To complete this step:

--- Imagine that you need to write a "drive a car" routine using the setup and loop functions.  Write the two loops and include the following commands.  If they should happen in a certain order, place them in order. Some commands may belong in both loops.

* If the road is curving, turn the steering wheel
* Apply pressure to the gas pedal
* Shift the car into gear / drive
* Turn the key
* Insert the key
* If it is dark, turn on the headlights
* If it is raining, turn on the windshield wipers

Task Discussion