// Define pins for entry and exit IR sensors
const int irEntryPin = 2; // Pin connected to IR receiver for entry
const int irExitPin = 3; // Pin connected to IR receiver for exit
// Define pins for LEDs and relay
const int greenLEDPin = 4; // Pin connected to green LED (entry)
const int redLEDPin = 5; // Pin connected to red LED (exit indicator)
const int relayPin = 6; // Pin connected to relay
// Variables
int peopleInRoom = 0;
bool entryBeamBroken = false;
bool exitBeamBroken = false;
unsigned long lastDebounceTimeEntry = 0;
unsigned long lastDebounceTimeExit = 0;
const unsigned long debounceDelay = 50; // Debounce time in milliseconds
void setup() {
pinMode(irEntryPin, INPUT); // Set entry IR receiver pin as input
pinMode(irExitPin, INPUT); // Set exit IR receiver pin as input
pinMode(greenLEDPin, OUTPUT); // Set green LED pin as output
pinMode(redLEDPin, OUTPUT); // Set red LED pin as output
pinMode(relayPin, OUTPUT); // Set relay pin as output
// Start serial communication for debugging
Serial.begin(9600);
}
void loop() {
// Read the state of the entry IR sensor
bool entryState = digitalRead(irEntryPin);
unsigned long currentTime = millis();
if (entryState == LOW) {
if ((currentTime - lastDebounceTimeEntry) > debounceDelay) {
if (!entryBeamBroken) {
entryBeamBroken = true;
peopleInRoom++;
Serial.print("People in room: ");
Serial.println(peopleInRoom);
// Blink the green LED to indicate entry
blinkLED(greenLEDPin);
// Keep relay on if there are people in the room
digitalWrite(relayPin, HIGH); // Activate relay
}
lastDebounceTimeEntry = currentTime;
}
} else {
entryBeamBroken = false;
}
// Read the state of the exit IR sensor
bool exitState = digitalRead(irExitPin);
if (exitState == LOW) {
if ((currentTime - lastDebounceTimeExit) > debounceDelay) {
if (!exitBeamBroken) {
exitBeamBroken = true;
if (peopleInRoom > 0) { // Prevent negative count
peopleInRoom--;
}
Serial.print("People in room: ");
Serial.println(peopleInRoom);
// Blink the red LED to indicate exit
blinkLED(redLEDPin);
// Turn off relay if the room is empty
if (peopleInRoom == 0) {
digitalWrite(relayPin, LOW); // Deactivate relay
}
}
lastDebounceTimeExit = currentTime;
}
} else {
exitBeamBroken = false;
}
}
// Function to blink an LED
void blinkLED(int ledPin) {
for (int i = 0; i < 3; i++) { // Blink the LED 3 times
digitalWrite(ledPin, HIGH);
delay(250); // LED on for 250 ms
digitalWrite(ledPin, LOW);
delay(250); // LED off for 250 ms
}
}