Instructables

Step 4: Programming the Project

Now that we have completed wiring up our project it is time to write some code. I'm including all the code below, but will talk about the theory a little first.

The code I've provided compiles to 1560 bytes in size. The Arduino handles programs up to 14336 bytes in size. This little project takes up over 10% of the Arduino's capacity, but this is REALLY not optimal code. It's a tutorial, so I've tried to be clear rather than efficient. I wouldn't be at all surprised to find it could be rewritten in half the space or less.

Every Arduino "sketch" has two mandatory areas: setup and loop. Setup executes ONCE after the program starts. This allows you to configure the initial state of the board: which pins are inputs, which are outputs, and whether outputs start off HIGH or LOW. The loop is the section of the program executived repeatedly as soon as setup has completed. There is no "end" or "exit" to an Arduino program -- there is nowhere to exit to! If you have experience programming, you'll immediately recognize the language used to program the Arduino is our good old buddy C. If not, you can pick up the basics just by going over my code and the other examples in the development kit. Many great C tutorials are also available on the web.

You can copy and paste the code into your Arduino development environment, then verify and upload it. If everything is right you should get blinky lights and be able to vary the speed by pressing the button.

Now a section-by-section breakdown of the sketch:

1) First we start by defining some variables. Much of this area is for human comprehension and could be skipped for the sake of efficiency. For example, I've defined a variable called "ledPinRed" and set it equal to 13 (I used three colors of LEDs -- the red one is connected to digital pin 13). I could have used "13" directly throughout the program, but that makes it much harder to comprehend. The comments next to the variables note what each is for.

2) Setup. Here I've set the pin to which the pushbutton is attached as an input pin. The Arduino will be looking to receive information (HIGH or LOW signals) there. I've set the LED connections to be outputs where the board will set the voltage as HIGH or LOW (5V or 0V) as appropriate. Finally, I turned on my green LED and made sure the others were turned OFF.

3) getButton: a function (just a container for code for any non-programmers reading this) that can be called from the main loop to find out if we've pressed the button. It keeps track of the current state of the button AND the previous state of the button the last time we looked at it. This allows us to respond only to individual button presses: holding down the button only counts as ONE press. This is important when the lights are changing very rapidly lest it be very tough to control.

4) changeLights: another function. This one gets called whenever we need to move from one LED to the next. The one that's on gets turned off and the next one in sequence gets turned on. It also updates the "currentLED" variable so we can keep track of which LED is currently active.

5) loop: The main loop. Here we first make a call to check on the button. If we find the button wasn't being pressed but now it is, we add to the "currentSpeed" variable. If we're going really fast, we reset currentSpeed back to 1 -- looping around so we can go back to slow speeds. After that...

...well, then we hit an ugly line that determines if it is time to change to the next LED. millis() is a built-in Arduino function that keeps track of how long the board has been running the current program. All we're doing here is finding out if enough time has gone by that we should change to the next light. If so, we call the "changeLights" function to make it happen.

Finally, here is the code (warning: it loses a little formatting when posted here, so it's not as pretty as it could be):

/*
  • Kevin's Arduino Tutorial
*
*
*/

// Note that these variables are all GLOBAL in scope, so they'll work inside our function calls
int ledPinRed = 13; // Set up digital outputs for LEDs
int ledPinYellow = 12;
int ledPinGreen = 11;
int switchPin = 2; // Set up to read the switch state from digital input 2
int currentLED = 1; //Green = 1, Yellow = 2, Red = 3
int currentSpeed = 1; // Determines how fast we switch between lights.
int buttonWas = 0; // The state of the switch (pushed = 1, not pushed = 0) last time we looked
int buttonIs = 0; // Current state of the switch
unsigned long timer = 0; // A timer to keep track of where we are.

void setup() // Runs once, when the program ("sketch") starts
{
pinMode(switchPin, INPUT); // Tells the Arduino to treat the switchPin as INPUT
pinMode(ledPinRed, OUTPUT); // Tells the Arduino that the Red LED pin is for OUTPUT
pinMode(ledPinYellow, OUTPUT);
pinMode(ledPinGreen, OUTPUT);
digitalWrite(ledPinGreen, HIGH); // Green LED is ON at start
digitalWrite(ledPinRed, LOW); // Red LED is OFF at start
digitalWrite(ledPinYellow, LOW); // Yellow LED is OFF at start
}

void getButton() { // Let's see what the button is doing, shall we?
buttonWas = buttonIs; // Set the old state of the button to be the current state since we're creating a new current state.
buttonIs = digitalRead(switchPin); // Read the button state
}

void changeLights() { // Turn OFF the currently lit LED and turn ON the next one.
timer=millis(); // reset our timer to the current time
if(currentLED==1) {
digitalWrite(ledPinGreen, LOW);
digitalWrite(ledPinYellow, HIGH);
}
if(currentLED==2) {
digitalWrite(ledPinYellow, LOW);
digitalWrite(ledPinRed, HIGH);
}
if(currentLED==3) {
digitalWrite(ledPinGreen, HIGH);
digitalWrite(ledPinRed, LOW);
}
currentLED++; // Add one to currentLED
if (currentLED==4) { currentLED=1; }
}

void loop() // This is our "main" loop. Arduino programs don't exit -- nowhere to exit TO!
{
getButton();
if((buttonIs==1)&&(buttonWas==0)) {
currentSpeed++; // Add one to the current delay because the button was pressed.
if(currentSpeed==15) { currentSpeed = 1; } // Loop around -- this sets us back to a slow rotation.
}
if (millis()>=timer+(1000/currentSpeed)) { // Time to change the lights!
changeLights();
}
}
 
Remove these adsRemove these ads by Signing Up
mvanderdeen2 years ago
this may be a little late (and possibly make me sound like an idiot) but here goes, i was wondering if thats all code or if your instructions are included in the coding above?
gunnk (author)  mvanderdeen2 years ago
Download the file at the end called "KevinsArduinoTutorial.cpp". That's JUST the code and you can use it as-is in the Arduino IDE (the program editor). In the text on this Instructables page, the code starts with the line:

/*

and ends with the final

}

on the page.

Don't worry about sounding like an idiot! If you aren't tackling new subjects where you don't know anything at all, then you aren't reaching your potential. The smartest people I know are the least afraid of looking like an idiot -- so they fearlessly ask "dumb questions" all the time!
Thanks for the help, and the motivation great instructable by the way :)
mcmahanly3 years ago
I'm completely new with programming. don't even know much about computers. Can somebody please explain to me what means what here. why am i typing int before everything. is there somewhere i can reference all of these terms?
gunnk (author)  mcmahanly3 years ago
I would recommend you learn a little basic programming first. Look for a tutorial on C as a starting point as the Arduino uses a bit of C and C++ for it's development.

The "int" before the variable names defines what kind of information the variable will store. In the case of "int" it means the value will be an integer. Other common variable types are "float" for floating point (decimal) numbers and "char" for characters. There are quite a few types. The full language reference for the Arduino is here: http://arduino.cc/en/Reference/HomePage