Parts Required
- Breadboard
- Red Diffused LED
- Yellow Diffused LED
- Green Diffused LED
- 3 x 150 ohm Resistors*
- Jumper Wires
Connect It Up
Connect your circuits as show Figure below. This time you connect three LEDs with the anode of each one going to Digital Pins 8, 9 and 10 via a 150 ohm resistor each.
Take a jumper wire from ground of the Arduino to ground rail at the top of the breadboard; a connected to the cathode. (For this simple circuit, it doesn't matter if the resistor is connected to the anode or cathode).
Image Source: Book Beggining Arduino. Page: 36 |
Enter the Code
int ledDelay = 5000;// delay in between changes
int redPin = 10;
int yellowPin = 9;
int greenPin = 8;
void setup (){
pinMode(redPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(greenPin, OUTPUT);
}
void loop(){
digitalWrite(redPin,HIGH);
delay(ledDelay); // wait 5 seconds
digitalWrite(yellowPin, HIGH);
delay(2000);// wait 2 seconds
digitalWrite(greenPin, HIGH); // turn green on
digitalWrite(redPin, LOW); // turn red off
digitalWrite(yellowPin, LOW); // turn yellow off
delay(ledDelay); // wait ledDelay milliseconds
digitalWrite(yellowPin,HIGH); // turn yellow on
digitalWrite(greenPin, LOW); // turn green off
delay(2000); // wait 2 seconds
digitalWrite(yellowPin, LOW); // turn yellow off
// now our loop repeats
}
Figure: The four states of the UK traffic lightsystem (Image Source: Book Beggining Arduino. Page: 37) |
Source: Excerpted and adapted from the Book Beginning Arduino, page 34-37.
Image Saurce: http://www.amazon.co.uk/Beginning-Arduino-Michael-McRoberts/dp/1430232404 |
Hope it's useful....