Wednesday, December 22, 2010

Arduino and The "Hello World!"

Arduino is a hardware electronics platform for easy prototyping and for easy creation of automated systems, more information can be found here www.arduino.cc.
This is it.
Arduino Duemilanove (2009 version)
As you can see it has USB port(yes! It is USB, it is standard type B) to connect with a computer. We need Arduino software to work with it (http://arduino.cc/en/Main/Software).
It is a tradition to write "Hello World" to the screen as a first program. But our hardware hasn't any screen :(. So we need to think something different. There is a simple tutorial at Arduino web site http://www.arduino.cc/en/Tutorial/BlinkingLED which is described as the "Hello world" of Arduino. So let see what it does. It uses an external LED, which connected to the board and periodically switch it on and off. But there is a build-in LED connected to the pin 13, so we can use it instead of connecting external one.
Built-in LED
The programming language is based on C++(actually it is based on Wiring...), but it doesn't mean you can write a program including iostream, cining, couting and etc ...
The console c++  programs has a mandatory "main(argc, argv)" function, on the Arduino there are two mandatory functions void setup() and void loop(). The first function will called when the Arduino is powered on(or reseted), and then the second function called repeatedly in infinite loop. So lets write a simple program which switch-on the built-in LED.
// Program: switch on the LED
int ledPin = 13; // the LED connected to pin 13
void setup()
{
pinMode(ledPin, OUTPUT); // Configure ledPin as output pin
digitalWrite(ledPin, HIGH); // Switch on the LED.  
}
void loop()
{
// Nothing to do
}

The build-in LED connected to 13th pin, so we need to configure it as an output pin. digitalWrite function write digital 1(+5V), which will switch on the LED.
Now it is time to run it. First of all create a new project in Arduino Software
New Project
copy above source code and verify it(it compiles the code)
Verify
Now the time is to connect Arduino hardware to the computer and then choose the right board type and serial port.
Select board type
Now verify it again and upload.
Upload
It automatically start to run. It can be rerun(reseted) by on-board reset button
On-board reset button
Now we will enhance our program, to switch on/off the LED periodically
// Program: periodically switch on/off the LED
int ledPin = 13; // the LED connected to pin 13
void setup()
{
    pinMode(ledPin, OUTPUT);   // Configure ledPin as output pin
}
void loop()
{
    digitalWrite(ledPin, HIGH);  // switch on the LED.  
    delay(1000);                       // delay 1000 milliseconds
    digitalWrite(ledPin, LOW);   // switch off the LED
    delay(1000);                       // delay 1000 milliseconds
}

Thats all, next time we will write a program using Arduino's serial port.

No comments:

Post a Comment