Group
Real-Time Programming in C++
Objective
1. Define a Sensor class that will store sensor details such as the type of sensor (e.g., motion, temperature) and the current status (active or inactive).
2. Define a method to simulate event detection for each sensor (e.g., motion detected, temperature exceeded).
3. When an event is detected, trigger an alarm by printing a message or activating a function.
4. Use a loop to continuously monitor the sensors and trigger the alarms when needed.
Create a program that simulates an alarm system with event detection.
Example C++ Exercise
Show C++ Code
#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;
}
Output
Motion detected! Alarm triggered!
Temperature threshold exceeded! Alarm triggered!
Motion detected! Alarm triggered!
Temperature threshold exceeded! Alarm triggered!
Door opened! Alarm triggered!
...