Grupo
Programación en Tiempo Real en C++
Ojetivo
Escriba un programa en C++ que simule un sistema de control de tráfico con semáforos. El programa debe alternar entre los colores del semáforo (rojo, amarillo y verde) a intervalos regulares, simulando el funcionamiento en tiempo real de un semáforo. Permita al usuario introducir la duración de cada color. El sistema debe repetir este ciclo continuamente.
Implemente un sistema de control de tráfico en tiempo real con semáforos.
Ejemplo de Código C++
Mostrar Código C++
#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;
}
Salida
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)
...
Comparte este ejercicio C++