Skip to content

1.5 Sample Answer

John-Paul Chouery edited this page Aug 24, 2024 · 2 revisions

Sample Code

Here’s a sample Arduino code for the LED traffic light project that uses three LEDs and a push button. This code simulates a simple traffic light system, lighting up the LEDs in sequence when the button is pressed.

// Constants for pin numbers
const int redLedPin = 10;    // Red LED connected to digital pin 10
const int yellowLedPin = 11; // Yellow LED connected to digital pin 11
const int greenLedPin = 12;  // Green LED connected to digital pin 12
const int buttonPin = 2;      // Push button connected to digital pin 2

// Variables for button state and current light state
int buttonState = 0;          // Variable for reading the pushbutton status
int currentLight = 0;         // 0: Red, 1: Yellow, 2: Green

void setup() {
  // Initialize LED pins as outputs
  pinMode(redLedPin, OUTPUT);
  pinMode(yellowLedPin, OUTPUT);
  pinMode(greenLedPin, OUTPUT);
  
  // Initialize pushbutton pin as input
  pinMode(buttonPin, INPUT);

  // Start serial communication
  Serial.begin(9600);
}

void loop() {
  // Read the state of the pushbutton value
  buttonState = digitalRead(buttonPin);

  // Check if the pushbutton is pressed
  if (buttonState == HIGH) {
    // Move to the next light state
    currentLight = (currentLight + 1) % 3; // Cycle through 0, 1, 2

    // Update LEDs based on the current light state
    if (currentLight == 0) {
      // Red light on
      digitalWrite(redLedPin, HIGH);
      digitalWrite(yellowLedPin, LOW);
      digitalWrite(greenLedPin, LOW);
      Serial.println("Red Light ON");
    } else if (currentLight == 1) {
      // Yellow light on
      digitalWrite(redLedPin, LOW);
      digitalWrite(yellowLedPin, HIGH);
      digitalWrite(greenLedPin, LOW);
      Serial.println("Yellow Light ON");
    } else if (currentLight == 2) {
      // Green light on
      digitalWrite(redLedPin, LOW);
      digitalWrite(yellowLedPin, LOW);
      digitalWrite(greenLedPin, HIGH);
      Serial.println("Green Light ON");
    }

    // Delay for a short period to prevent multiple readings
    delay(500); // Debounce delay
  }
}

Explanation of the Code:

  • Pin Setup: The red, yellow, and green LEDs are connected to digital pins 10, 11, and 12, respectively. The push button is connected to digital pin 2.
  • Loop Logic: The loop() function continuously checks the state of the push button. When pressed, it cycles through the traffic light states (red, yellow, green).
  • LED Control: The digitalWrite() function is used to turn on the appropriate LED while turning off the others. The current light state is printed to the Serial Monitor for debugging.
  • Debounce Delay: A small delay is added after a button press to prevent multiple transitions from being registered due to mechanical bounce.

Feel free to modify this code or add additional functionality to your project!

Clone this wiki locally