Arduino Project for Traffic Light: Simple Code and Setup
digitalWrite() to control LEDs representing red, yellow, and green lights in sequence. You connect LEDs to Arduino pins and write a loop to turn them on and off with delay() for timing.Syntax
The basic syntax for controlling LEDs in an Arduino traffic light project involves setting pin modes and using digitalWrite(pin, HIGH) to turn an LED on and digitalWrite(pin, LOW) to turn it off. The delay(milliseconds) function pauses the program to keep the light on for a set time.
pinMode(pin, OUTPUT): Sets the pin as an output to control an LED.digitalWrite(pin, HIGH): Turns the LED on.digitalWrite(pin, LOW): Turns the LED off.delay(ms): Waits for the specified milliseconds.
void setup() { pinMode(2, OUTPUT); // Red LED pinMode(3, OUTPUT); // Yellow LED pinMode(4, OUTPUT); // Green LED } void loop() { digitalWrite(2, HIGH); // Red ON delay(5000); // Wait 5 seconds digitalWrite(2, LOW); // Red OFF digitalWrite(3, HIGH); // Yellow ON delay(2000); // Wait 2 seconds digitalWrite(3, LOW); // Yellow OFF digitalWrite(4, HIGH); // Green ON delay(5000); // Wait 5 seconds digitalWrite(4, LOW); // Green OFF }
Example
This example shows a simple traffic light sequence using three LEDs connected to pins 2, 3, and 4. The red light stays on for 5 seconds, yellow for 2 seconds, and green for 5 seconds, repeating endlessly.
void setup() { pinMode(2, OUTPUT); // Red LED pinMode(3, OUTPUT); // Yellow LED pinMode(4, OUTPUT); // Green LED } void loop() { // Red light digitalWrite(2, HIGH); digitalWrite(3, LOW); digitalWrite(4, LOW); delay(5000); // Yellow light digitalWrite(2, LOW); digitalWrite(3, HIGH); digitalWrite(4, LOW); delay(2000); // Green light digitalWrite(2, LOW); digitalWrite(3, LOW); digitalWrite(4, HIGH); delay(5000); }
Common Pitfalls
Common mistakes include not setting the pin modes to OUTPUT, which prevents LEDs from lighting up. Another error is forgetting to turn off other LEDs before turning one on, causing multiple lights to be on simultaneously. Also, wiring LEDs without resistors can damage them or the Arduino.
/* Wrong: Missing pinMode setup */ void setup() { // pinMode calls missing } void loop() { digitalWrite(2, HIGH); // Won't work properly delay(1000); } /* Correct: Proper pinMode setup */ void setup() { pinMode(2, OUTPUT); } void loop() { digitalWrite(2, HIGH); delay(1000); digitalWrite(2, LOW); delay(1000); }
Quick Reference
- pinMode(pin, OUTPUT): Prepare pin to control LED.
- digitalWrite(pin, HIGH): Turn LED on.
- digitalWrite(pin, LOW): Turn LED off.
- delay(ms): Pause program for timing.
- Use resistors: Protect LEDs and Arduino pins.