Group
Real-Time Programming in C++
Objective
Write a C++ program that simulates a traffic control system with traffic lights. The program should cycle through the traffic light colors (red, yellow, and green) at regular intervals, simulating the real-time operation of a traffic light. Allow the user to input the duration for each light color. The system should continuously repeat this cycle.
Implement a real-time traffic control system with traffic lights.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the input-output stream library
#include <thread> // Include the thread library for controlling time intervals
#include <chrono> // Include the chrono library for time manipulation
using namespace std;
// Function to simulate the traffic light control system
void trafficLightControl(int redDuration, int yellowDuration, int greenDuration) {
while (true) { // Infinite loop to simulate continuous traffic light cycles
// Simulate Red Light
cout << "RED LIGHT - Stop" << endl;
this_thread::sleep_for(chrono::seconds(redDuration)); // Wait for the specified red light duration
// Simulate Yellow Light
cout << "YELLOW LIGHT - Prepare to stop or go" << endl;
this_thread::sleep_for(chrono::seconds(yellowDuration)); // Wait for the specified yellow light duration
// Simulate Green Light
cout << "GREEN LIGHT - Go" << endl;
this_thread::sleep_for(chrono::seconds(greenDuration)); // Wait for the specified green light duration
}
}
int main() {
int redDuration, yellowDuration, greenDuration;
// Ask the user to enter the duration for each light color
cout << "Enter the duration for RED light in seconds: ";
cin >> redDuration;
cout << "Enter the duration for YELLOW light in seconds: ";
cin >> yellowDuration;
cout << "Enter the duration for GREEN light in seconds: ";
cin >> greenDuration;
// Start the traffic light control system with the specified durations
trafficLightControl(redDuration, yellowDuration, greenDuration);
return 0;
}
Output
Enter the duration for RED light in seconds: 5
Enter the duration for YELLOW light in seconds: 2
Enter the duration for GREEN light in seconds: 3
RED LIGHT - Stop
(Yellow light cycle after 5 seconds)
YELLOW LIGHT - Prepare to stop or go
(Green light cycle after 2 seconds)
GREEN LIGHT - Go
(Red light cycle after 3 seconds)
...