Grupo
Programación en Tiempo Real en C++
Ojetivo
1. Defina una clase de sensor que almacene detalles del sensor, como el tipo (p. ej., movimiento, temperatura) y su estado actual (activo o inactivo).
2. Defina un método para simular la detección de eventos para cada sensor (p. ej., movimiento detectado, temperatura excedida).
3. Cuando se detecte un evento, active una alarma imprimiendo un mensaje o activando una función.
4. Utilice un bucle para monitorizar continuamente los sensores y activar las alarmas cuando sea necesario.
Cree un programa que simule un sistema de alarma con detección de eventos.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
using namespace std;
// Sensor class to represent a sensor in the alarm system
class Sensor {
public:
string type; // Type of the sensor (e.g., motion, temperature)
bool status; // Sensor status (true = active, false = inactive)
// Constructor to initialize the sensor type and status
Sensor(string type, bool status) : type(type), status(status) {}
// Function to simulate the detection of an event (motion or temperature breach)
void detectEvent() {
if (status) { // If the sensor is active
// Randomly simulate an event detection for demonstration purposes
if (type == "Motion" && rand() % 2 == 0) {
cout << "Motion detected! Alarm triggered!" << endl;
}
else if (type == "Temperature" && rand() % 2 == 0) {
cout << "Temperature threshold exceeded! Alarm triggered!" << endl;
}
else if (type == "Door" && rand() % 2 == 0) {
cout << "Door opened! Alarm triggered!" << endl;
}
}
}
};
// Function to simulate continuous monitoring of sensors
void monitorSensors(Sensor &sensor) {
while (true) {
sensor.detectEvent(); // Check if an event is detected by the sensor
this_thread::sleep_for(chrono::seconds(1)); // Wait for 1 second before checking again
}
}
int main() {
// Create some sensors for demonstration purposes
Sensor motionSensor("Motion", true); // Motion sensor (active)
Sensor temperatureSensor("Temperature", true); // Temperature sensor (active)
Sensor doorSensor("Door", true); // Door sensor (active)
// Start monitoring the sensors in separate threads
thread motionThread(monitorSensors, ref(motionSensor));
thread tempThread(monitorSensors, ref(temperatureSensor));
thread doorThread(monitorSensors, ref(doorSensor));
// Join the threads to run them simultaneously
motionThread.join();
tempThread.join();
doorThread.join();
return 0;
}
Salida
Motion detected! Alarm triggered!
Temperature threshold exceeded! Alarm triggered!
Motion detected! Alarm triggered!
Temperature threshold exceeded! Alarm triggered!
Door opened! Alarm triggered!
...
Comparte este ejercicio C++