Magnetic contact switch Arduino project

The essential sensors for home automation are the following:

  • the movement sensor like the PIR sensor we’ve made used of here
  • the flood sensor
  • the temperature sensor
  • the humidity sensor

Today, we are going to add one more sensor to the list: the Reed switch.

The Reed switch is a simple contact that closes when a magnet is brought close to it. Thanks to this effect we can sense when doors or windows are opened or closed.

A lot of alarm systems uses not only movement sensors but also reed-switches that are installed inside the windows. Reed switches can also be useful for other applications: A magnet and reed switch mounted on a bicycle can help calculate the speed of the bicycle based on the RPM of the wheels.

Today we will make a simple device that will light up a LED when a window is opened and if it is opened for 15 minutes, it turns on a buzzer to remind you to close it.

I personally need a device like that now, we are having our winter now and it is very cold outside. Sometimes I need to open the window to have some fresh air in the room. Here is where the device will help me remember to close the window in case I forget, especially when I am in the other room.

Parts needed

Here is the list of parts we need to this project:

The schematic

When you have all the components, you can start with the connection. Below you can find the schematic of the project. To clarify and simplify this, keep in mind that all red cables are 5V and all blue cables are GND.

The code

And the code. I made a simple rising edge detection with a bool variable to make the code detect when the high state occurs, save the millis value in the variable and power the LED. At the same time, our code detects if the window is open for more than 15 minutes. If it is, the buzzer turns on.

bool high_all_the_time = false;
long int window_opened_at;
void setup() {
pinMode(7, INPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
digitalWrite(7, HIGH);


void loop() {
if(digitalRead(7) == LOW && high_all_the_time == false){
high_all_the_time = true;
window_opened_at = millis();
digitalWrite(9, HIGH);
}else if(digitalRead(7) == HIGH){
digitalWrite(9, LOW);
high_all_the_time = false;

if(millis() > (window_opened_at + (1000 * 30)) && high_all_the_time){
digitalWrite(8, HIGH);
digitalWrite(8, LOW);


Here is the video of how it works, to make it shorter I change the time from 15 minutes to 30 seconds. After this time if the window is open, the buzzer turns on.

And that is it for this session.


Related Posts