Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Code

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

// Define pin numbers for LEDs and pushbutton

const int carRed = 13;

const int carYellow = 12;

const int carGreen = 11;

const int pedRed = 3;

const int pedGreen = 2;

const int buttonPin = 7;

// Define time intervals for each state (in milliseconds)

const long carRedTime = 45000;

const long carYellowTime = 15000;

const long carGreenTime = 45000;

const long pedGreenTime = 45000;

// Define initial states for traffic lights and pedestrian light

int carState = 0; // 0 = red, 1 = green, 2 = yellow

int pedState = 0; // 0 = red, 1 = green

int buttonState = 0;

int lastButtonState = 0;

unsigned long lastCarTime = 0;

unsigned long lastPedTime = 0;

void setup() {

pinMode(carRed, OUTPUT);

pinMode(carYellow, OUTPUT);
pinMode(carGreen, OUTPUT);

pinMode(pedRed, OUTPUT);

pinMode(pedGreen, OUTPUT);

pinMode(buttonPin, INPUT_PULLUP); // internal pull-up resistor to avoid floating pin

void loop() {

// Check button state

buttonState = digitalRead(buttonPin);

if (buttonState == LOW && lastButtonState == HIGH) {

// Pedestrian has pressed the button, so switch car traffic light to red

carState = 0;

lastCarTime = millis(); // reset car timer

lastButtonState = buttonState;

// Check car traffic light state

switch (carState) {

case 0: // red

digitalWrite(carRed, HIGH);

digitalWrite(carYellow, LOW);

digitalWrite(carGreen, LOW);

if (millis() - lastCarTime >= carRedTime) {

// Switch to yellow

carState = 1;
lastCarTime = millis(); // reset car timer

break;

case 1: // yellow

digitalWrite(carRed, LOW);

digitalWrite(carYellow, HIGH);

digitalWrite(carGreen, LOW);

if (millis() - lastCarTime >= carYellowTime) {

// Switch to green

carState = 2;

lastCarTime = millis(); // reset car timer

break;

case 2: // green

digitalWrite(carRed, LOW);

digitalWrite(carYellow, LOW);

digitalWrite(carGreen, HIGH);

if (millis() - lastCarTime >= carGreenTime) {

// Switch to yellow

carState = 3;

lastCarTime = millis(); // reset car timer

break;

case 3: // yellow

digitalWrite(carRed, LOW);
digitalWrite(carYellow, HIGH);

digitalWrite(carGreen, LOW);

if (millis() - lastCarTime >= carYellowTime) {

// Switch to red

carState = 0;

lastCarTime = millis(); // reset car timer

break;

// Check pedestrian traffic light state

if (carState == 0 || carState == 3) {

// Car traffic light is red or yellow, so pedestrian light should be green

digitalWrite(pedRed, LOW);

digitalWrite(pedGreen, HIGH);

if (millis() - lastPedTime >= pedGreenTime) {

// Switch to red

pedState = 0;

lastPedTime = millis(); // reset pedestrian timer

} else {

// Car traffic light is green, so pedestrian light should be red

digitalWrite(pedRed, HIGH);

digitalWrite(pedGreen, LOW);

pedState = 1; // set pedestrian state to green to avoid false button trigger

}
}

You might also like