Learning to Program the Arduino

Blink Those LEDs

For the first sketch, let's blink an LED and then extend it to blink multiple LEDs alternately. Before the software part, let's first set up the circuit to connect the LED to the Arduino. The completed circuit should look like Figure 2.

Figure 2. Circuit for a Single LED Blink

Next, in your Arduino IDE, open the sketch in Examples→Basics→Blink, which should look like Listing 1.

Listing 1. Simple LED Blink Sketch


/*
 Blink
 Turns on an LED on for one second,
 then off for one second, repeatedly.
 This example code is in the public domain.
 */

void setup() {
 // initialize the digital pin as an output.
 // Pin 13 has an LED connected on most Arduino boards:
 pinMode(13, OUTPUT);
}

void loop() {
 digitalWrite(13, HIGH);   // set the LED on
 delay(1000);              // wait for a second
 digitalWrite(13, LOW);    // set the LED off
 delay(1000);              // wait for a second
}

As you can see from that sketch and the circuit diagram, the LED is connected to the digital pin 13 of the Arduino. Once you verify (compile) the sketch and upload it to the Arduino board, you should see the blinking LED.

Because this is your first sketch, take some time to understand the general framework of an Arduino sketch. If you are familiar with C or C++, you will notice that you have two functions in this sketch: setup() and loop(). The code that you write in setup() is meant for initialization and is executed once the sketch is uploaded to the board. The code in loop() is executed repeatedly as long as the power to the Arduino is supplied. Even if you power off the Arduino and power it back on, the sketch still resides until you overwrite it with another sketch. An Arduino sketch should be saved in a file with the extension pde and is stored in a directory of the same name.

For the next sketch, let's connect multiple LEDs and blink them alternately to create a cool rippling effect. (You might want to connect more than three LEDs of different colors.) The circuit for this sketch is shown in Figure 3.

Figure 3. Circuit for Multiple Blinking LEDs

Listing 2. Multiple LED Blink Sketch


/* Multiple LED Blinking program
  Amit Saha

*/

// constants won't change. Used here to
// set pin numbers:
const int numPins = 3;
const int ledPin [] =  {11,12,13};   // the number of LED pins

int interval = 100;    // interval at which to blink (milliseconds)

void setup() {
  // Iterate over each of the pins and set them as output
  for(int i=0;i<numPins;i++)
    pinMode(ledPin[i], OUTPUT);
}

/* Loop until death */
void loop()
{
  for(int i=0;i<numPins;i++)
  {
    digitalWrite(ledPin[i],HIGH);
    delay(interval);
    digitalWrite(ledPin[i],LOW);
    delay(interval);
  }
}

Once you have uploaded this sketch to your Arduino UNO board, your LEDs should put on a colorful performance.

Analog Sensors

In the first sketch, you turned the LED on and off by writing to the Arduino's digital pin. What if you wanted something in between—say, to fade on and off? Say hello to a tiny little device called a potentiometer. To set up the circuit, connect the central pin of the potentiometer to the analog pin 0, and the other two pins to the +5V supply and ground, respectively. The LED should be connected as in the first sketch.

Listing 3. Fade an LED On/Off Using a Linear Potentiometer


/* Using potentiometer to fade on/off an LED
*  Original code notice below:
* ------------------------------
* Demonstrates analog input by reading an analog sensor on
* analog pin 0 and turning on and off a light emitting
* diode (LED) connected to digital pin 13.
* The amount of time the LED will be on and off
* depends on the value obtained by analogREAD().
* Created by David Cuartielles
* Modified 16 Jun 2009
* By Tom Igoe
* http://arduino.cc/en/Tutorial/AnalogInput
*/

int sensorPin = 0;
int ledPin = 13;
int sensorValue = 0;

void setup() {
     //declare the ledPin as an OUTPUT:
     pinMode(ledPin, OUTPUT);
     Serial.begin(9600);
}

void loop() {
        sensorValue = analogRead(sensorPin);//

        digitalWrite(ledPin, HIGH);

        delay(sensorValue);

        digitalWrite(ledPin, LOW);

        delay(sensorValue);
}

In Listing 3, you can see that the reading from the potentiometer is used to control the delay time, so the effect of fading in and out is produced.

Next, let's use an electronic component called a flex sensor to (you guessed it) control an LED. Basically, let's use the flex sensor in place of the potentiometer of the earlier circuit. A flex sensor is an analog sensor whose resistance changes with its bending angle. You will see that the resistance changes as you bend on either side—increasing on one side and decreasing on the other. The Arduino sketch is shown in Listing 4.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Really interesting

marksen's picture

Arduino is a really intersting project because its way to use are limitless. It can be adapted to many things and it's quite easy to program.

I love the Arduino! Thanks

Pit's picture

I love the Arduino! Thanks for the interesting article.

Processing, C/C++ and Arduino

SomeTom's picture

...a language that looks very similar to C and is based on Processing.

Well, I'd rather say it's a language that looks like Processing (Arduino is using the Processing IDE) but is based on C/C++. There's AVR's version of gcc under the hood, while Processing is running on top of Java.
Although the simplified C/C++ inside the IDE is looking mostly like Processing, Arduino really is not Processing at all. If you used to play around with Processing before you tried to code some Arduino you might make some weird experiences, as it really seems to be the same - until you try to try to initialize arrays or do some string operations.
After hours of really weird behaviour, I looked a little deeper into the docs and was quite surprised to find out that I had unknowingly been running Java-like code through a C-compiler for half a day :)
The funniest thing about it was that it actually worked most of the time...

Thank you for the comment.

Amit Saha's picture

Thank you for the comment. Perhaps, "based on Processing" is not very true.

However to me, the language looks "very" C. And yes as you pointed out, its really gcc-avr down below as also pointed out in the later parts of the article. My experience with Processing is not beyond a basic level, so I came to Arduino "from" C, rather than processing.

Cheers,
Amit

Great article. Just a brief

Fabpicca's picture

Great article.
Just a brief observation.
Arduino doesn't stand for "good friend" in Italian (I'm Italian). As far as I know Arduino is the name of the cafè Arduino inventors where used to meet.

But Wikipedia says so?

AmitSaha's picture

Hello: Thanks for your comment. I am sorry if I got it wrong, But Wikipedia has this: "Arduino" is an Italian masculine first name, meaning "strong friend". The English version of the name is "Hardwin".(From: http://en.wikipedia.org/wiki/Arduino#History)

Cheers,
Amit

You're mistaken.

Anonymous's picture

Amit is a Hebrew name which has the meaning "Friend" but it's not correct to say that Amit is the Hebrew word for friend. Just because the name's origin is Italian doesn't mean it's a current Italian word for something.

Name of Cafe, Name of King

MoChaMan69's picture

The name Arduino comes from the cafe the founder(s) frequented where they thought of the project . Cafe Arduino takes it's name from medievel king that briefly ruled the area . I can't find my source right now but it's something like King of Ardo , therefore he was an Arduino , hence Cafe Arduino , hence the Arduino Project . Much of this comes from the IEEE article a few months ago .

Unfortunately, the lack of research in the first sentence makes me doubt the entire 5 page article . I'll glance at it later anyway in case there's something useful . - MC

I'm from Italy, therefore I

From_Italy's picture

I'm from Italy, therefore I can give a definitive answer. Arduino is the name of a bar in Ivrea (Piedmont, Italy) frequented by the (Italian) creators of the open source framework. The bar was named after Arduin of Ivrea, first King of Italy from 1002 to 1017. By the way, Arduino is not a common name nowadays in Italy

actuators

Roland's picture

The IO pins can't drive much: 5v and 40ma each, not to exceed 120ma total. You need a tiny relay to do anything more than power an LED, and even there you need to limit the current to prevent burnout. I have had luck with tiny reed relays connected directly to the IO pins. See www.elexp.com p/n 22RD5, with 5v/500ohm coils. These draw only 10ma. Buy more than you need and test them all. Two of the 12 I ordered had open coils. And put a diode across any relay coils. The Arduino already has pull-up/pull-down diodes on all the pins, which is why the AD pins read around 2.5v if not connected. Remember, when you stop applying any power to a coil, the magnetic field collapses which produces a brief voltage spike. Also, any of the above reed relays can also be used as magnetic sensors to detect an open window, for instance. Just glue a small magnet nearby.

Figures 2 and 3

OP's picture

The LEDs shown in figures 2 and 3 are shorted as illustrated. The edge rows on most (if not all) breadboards are buses.

Ground wires and tty

SomeTom's picture

Right. Also the ground wire of the rightmost LED does not connect anywhere. It should be in the same column as the LED it is supposed to ground.
If you are using a recent version of Arduino (and a newer original board) you are more likely to find /dev/ttyUSB0 that /dev/ttyACM0. (Just a typo, but /dev/tttyACM0 won't do any good at all).

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix