Door alarm (reed switch)
A reed switch on the door frame closes while the door's magnet is near; open the door for more than five seconds and the alarm sounds.
Input · Beginner
In a real product: Home security system (Smart home): Door contacts trigger the alarm when a door opens too long.
Door and window sensors are reed switches: two springy contacts in a glass tube that close while a magnet is near. The switch goes on the frame and the magnet on the door, so the contact is closed while the door is shut.
What you'll learn
- Wiring a contact with
INPUT_PULLUP: closed reads LOW, open reads HIGH - A small state machine: shut, open and counting down, alarm
- Debouncing a mechanical contact by requiring a steady reading
How it works
The switch joins pin 4 to GND while the magnet is near. With the pull-up on, the pin reads LOW with the door shut and HIGH when it opens. The sketch only believes a change that has held for 30 ms (the reeds bounce). Opening the door starts a five-second grace period with the LED on; if it is still open after that, the buzzer sounds until it is shut.
Try this
- Click the reed switch to take the magnet away (the door opens), and back within five seconds: no alarm.
- Leave it open: the alarm starts. Shut it: the alarm stops.
- Change the switch's contact to
NC(normally closed): what has to change in the sketch?
sketch.ino
// A door alarm: a reed switch from pin 4 to GND is closed while the door's magnet is near. Opened for more than five
// seconds, the buzzer on pin 8 sounds; the LED on pin 13 shows the door is open.
const int REED = 4, BUZZER = 8, LED = 13;
const unsigned long GRACE_MS = 5000, DEBOUNCE_MS = 30;
bool doorOpen = false;
unsigned long openedAt = 0;
bool readDoor() {
static bool stable = false, last = false;
static unsigned long changedAt = 0;
bool now = digitalRead(REED) == HIGH; // HIGH: the contact is open, the magnet away
if (now != last) { last = now; changedAt = millis(); }
if (millis() - changedAt >= DEBOUNCE_MS) stable = last;
return stable;
}
void setup() {
Serial.begin(9600);
pinMode(REED, INPUT_PULLUP);
pinMode(LED, OUTPUT);
}
void loop() {
bool open = readDoor();
if (open && !doorOpen) { openedAt = millis(); Serial.println("Door opened"); }
if (!open && doorOpen) { noTone(BUZZER); Serial.println("Door shut"); }
doorOpen = open;
digitalWrite(LED, open);
if (open && millis() - openedAt >= GRACE_MS) tone(BUZZER, 1000);
}