arduino-sketches/door-sensor/door-sensor.ino

92 lines
2.2 KiB
Arduino
Raw Normal View History

2025-04-10 10:34:47 -03:00
#include <IRremote.hpp>
2025-04-10 10:50:54 -03:00
#include "melody.h"
2025-04-10 10:34:47 -03:00
#define IR_RECEIVE_PIN 7
2025-04-10 10:50:54 -03:00
2025-04-10 10:34:47 -03:00
const int DOOR_SENSOR_PIN = 13;
2025-04-10 10:50:54 -03:00
/* Connections:
* Door Sensor: Gnd & 13
* Buzzer: Gnd & 8
* Led Receptor: 7 & Gnd & 5V
*/
2025-04-10 10:34:47 -03:00
int currentDoorState; // current state of door sensor
int lastDoorState; // previous state of door sensor
void setup()
{
Serial.begin(115200); // // Establish serial communication
IrReceiver.begin(IR_RECEIVE_PIN, ENABLE_LED_FEEDBACK); // Start the receiver
pinMode(DOOR_SENSOR_PIN, INPUT_PULLUP);
currentDoorState = digitalRead(DOOR_SENSOR_PIN); // read state
2025-04-10 10:50:54 -03:00
if(useTimerFreeTone){
Serial.println("configure to use timer free tone");
}
2025-04-10 10:34:47 -03:00
}
int lastCmd;
unsigned long lastTime;
void loop() {
handleDoor();
if (IrReceiver.decode()) {
// Serial.println(IrReceiver.decodedIRData.decodedRawData, HEX); // Print "old" raw data
// IrReceiver.printIRResultShort(&Serial); // Print complete received data in one line
// IrReceiver.printIRSendUsage(&Serial); // Print the statement required to send this data
// if(lastCmd == IrReceiver.decodedIRData.command && lastTime + 2000 > millis() )
// {
// IrReceiver.resume();
// return;
// }
switch(IrReceiver.decodedIRData.command)
{
case 67:
Serial.println("Play");
playTone();
break;
default:
Serial.print("unk: ");
Serial.println(IrReceiver.decodedIRData.command);
}
//IrReceiver.printIRResultShort(&Serial); // Print complete received data in one line
// lastTime = millis();
// lastCmd=IrReceiver.decodedIRData.command;
//Serial.println(IrReceiver.decodedIRData.command);
IrReceiver.resume();
}
}
void handleDoor(){
lastDoorState = currentDoorState; // save the last state
currentDoorState = digitalRead(DOOR_SENSOR_PIN); // read new state
if (lastDoorState == LOW && currentDoorState == HIGH) { // state change: LOW -> HIGH
Serial.println("The door-opening event is detected");
playTone();
}
else
if (lastDoorState == HIGH && currentDoorState == LOW) { // state change: HIGH -> LOW
Serial.println("The door-closing event is detected");
// TODO: turn off alarm, light or send notification ...
}
}
2025-04-10 10:50:54 -03:00
2025-04-10 10:34:47 -03:00