Program 1 – Hello World
In normal programming languages, the first program traditionally prints Hello World to a screen. With micro-controllers, the first program usually just makes an LED flash.
Using 4 connecting wires set up the following circuit using your arduino and an LED
The LED pin marked – needs to connect to a GND pin
The LED pin marked R needs to connect to signal pin 9, G and B should be connected to pins 10 and 11.
In the arduino IDE, type the following code:
#define LEDpin 9
void setup ()
{
pinMode(LEDpin, OUTPUT);
}
void loop ()
{
digitalWrite(LEDpin, HIGH);
delay(2000);
digitalWrite(LEDpin, LOW);
delay(1000);
}
How it works:
#define LEDpin 9
This line tells the arduino that any time we use the constant name LEDpin we want the arduino to do something with digital pin 9.
void setup ()
{
pinMode(LEDpin, OUTPUT);
}
This setup function which all programs must have sets the pin for the LED into output mode. Other options are INPUT and INPUT_PULLUP (used later)
void loop ()
{
digitalWrite(LEDpin, HIGH);
delay(2000);
digitalWrite(LEDpin, LOW);
>delay(1000);
}
This is the main part of the arduino program. DigitalWrite() sends data (either high (5V) or low (0V)) to the pin. delay() pauses the arduino program for the given number of milliseconds (2000 miliseconds equals 2 seconds). When the program gets to the end of the loop, it returns to the beginning and starts again.
Challenges
-
- Modify the code so that the LED flashes blue instead of red.
#define LEDpin 11
void setup ()
{
pinMode(LEDpin, OUTPUT);
}
void loop ()
{
digitalWrite(LEDpin, HIGH);
delay(2000);
digitalWrite(LEDpin, LOW);
delay(1000);
}
-
- Modify the code so that the LED flashes quickly.
#define LEDpin 9
void setup ()
{
pinMode(LEDpin, OUTPUT);
}
void loop ()
{
digitalWrite(LEDpin, HIGH);
delay(200);
digitalWrite(LEDpin, LOW);
delay(200);
}
#define LEDpin 9
int t=200;
void setup ()
{
pinMode(LEDpin, OUTPUT);
}
void loop ()
{
digitalWrite(LEDpin, HIGH);
delay(t);
digitalWrite(LEDpin, LOW);
delay(t);
}
-
- Modify the code so that the LED flashes red, then green, then blue.
#define Redpin 9
#define Grnpin 10
#define Blupin 11
int t=200;
void setup ()
{
pinMode(Redpin, OUTPUT);
pinMode(Grnpin, OUTPUT);
pinMode(Blupin, OUTPUT);
}
void loop ()
{
digitalWrite(Redpin, HIGH);
delay(t);
digitalWrite(Redpin, LOW);
delay(t);
digitalWrite(Grnpin, HIGH);
delay(t);
digitalWrite(Grnpin, LOW);
delay(t);
digitalWrite(Blupin, HIGH);
delay(t);
digitalWrite(Blupin, LOW);
delay(t);
}
#define Redpin 9
#define Grnpin 10
#define Blupin 11
int t=200;
int Pins[]=(Redpin,Grnpin,Blupin);
void setup ()
{
pinMode(Redpin, OUTPUT);
pinMode(Grnpin, OUTPUT);
pinMode(Blupin, OUTPUT);
}
void loop ()
{
for(int i=0;i<3;i++)
{
digitalWrite(Pins[i], HIGH);
delay(t);
digitalWrite(Pins[i], LOW);
delay(t);
}
}
