#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// for the address of the lcd diaplay
LiquidCrystal_I2C lcd(0x27, 16, 2);
// defining the pins for all the leds
#define r1 2
#define y1 3
#define g1 4
#define r2 5
#define y2 6
#define g2 7
#define b1 8
#define b2 9
// cars in lane 1 and lane 2
int c1 = 0;
int c2 = 0;
// timer for changes in traffic lights
unsigned long prev_time = 0;
// default time duration for green
const int g_default = 5000;
// time duration for yellow
const int y_time = 2000;
// current light
int current = 0;
void setup() {
pinMode(r1, OUTPUT);
pinMode(y1, OUTPUT);
pinMode(g1, OUTPUT);
pinMode(r2, OUTPUT);
pinMode(y2, OUTPUT);
pinMode(g2, OUTPUT);
pinMode(b1, INPUT_PULLUP);
pinMode(b2, INPUT_PULLUP);
Serial.begin(9600);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Lane 1: 0");
lcd.setCursor(0, 1);
lcd.print("Lane 2: 0");
}
void loop() {
button();
traffic_lights();
}
void button() {
if (digitalRead(b1) == LOW) {
Serial.println("Lane 1 Button Pressed");
c1 = c1 + 1;
updateLCD();
delay(200);
}
if (digitalRead(b2) == LOW) {
Serial.println("Lane 2 Button Pressed");
c2 = c2 + 1;
updateLCD();
delay(200);
}
}
// Function to handle traffic light control
void traffic_lights() {
unsigned long cur_time = millis();
if (current == 0) {
if (cur_time - prev_time >= g_time(c1)) {
prev_time = cur_time;
current = 1; // Move to Lane 1 Yellow
digitalWrite(g1, LOW);
digitalWrite(y1, HIGH);
// resetting the car count's in the lane assuming that all cars left the signal
c1 = 0;
updateLCD();
}
else {
digitalWrite(r2, HIGH);
digitalWrite(g1, HIGH);
}
}
else if (current == 1) {
if (cur_time - prev_time >= y_time) {
prev_time = cur_time;
current = 2;
digitalWrite(y1, LOW);
digitalWrite(r1, HIGH);
digitalWrite(r2, LOW);
}
}
else if (current == 2) {
if (cur_time - prev_time >= g_time(c2)) {
prev_time = cur_time;
current = 3;
digitalWrite(g2, LOW);
digitalWrite(y2, HIGH);
c2 = 0;
updateLCD();
}
else {
digitalWrite(r1, HIGH);
digitalWrite(g2, HIGH);
}
}
else if (current == 3) { // Lane 2 Yellow
if (cur_time - prev_time >= y_time) {
prev_time = cur_time;
current = 0; // Move to Lane 1 Green
digitalWrite(y2, LOW);
digitalWrite(r2, HIGH);
digitalWrite(r1, LOW);
}
}
}
// to calculate change in green light's time
int g_time(int carCount) {
return g_default + (carCount * 500);
}
void updateLCD() {
lcd.setCursor(0, 0);
lcd.print("Lane 1: ");
lcd.print(c1);
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print("Lane 2: ");
lcd.print(c2);
lcd.print(" ");
}