Topic: Mechatronics/Robotics

Arduino door sensor

Difficulty

Medium

Objective

Program a microcontroller to run a simple piece of code that lets you know when your door has been opened.

Outline

When the reed switch is aligned (the door is closed), the magnet on the door pulls the switch closed, closing the circuit which can be read by the Arduino and displayed on the screen.

Equipment

  • A computer
  • Arduino UNO
  • USB Type A/B Cable
  • Door sensor (sometimes called a reed switch)

Method

1

On your computer, make sure you have Arduino IDE installed for your operating system. Follow this guide to make sure you have everything set up correctly (https://www.arduino.cc/en/Guide/ArduinoUno)

2

Mount the reed switch on a door you want to monitor

3

Connect one of the reed switch leads to the GND pin on the Arduino, and the other lead to pin number 13. This means that if we read from PIN 13 on the Arduino:

  1. When the door is closed, PIN13 will be connected to ground. This is called a LOW signal
  2. When the door is open, the switch will be floating. We want this to be the opposite of LOW, which is HIGH. In order to do this, we need to use a pullup resistor which can be set in software.
4

Plug in the Arduino and open the Arduino IDE. Copy the following code:


//ResMed Stem Activity.Arduino Door Sensor 

const int DOOR_SENSOR_PIN = 13; // Arduino pin connected to door sensor's pin
int doorState; // Variable to store the state of the door (HIGH == open, LOW == closed)

void setup() {
    Serial.begin(9600); // initialize serial
    pinMode(DOOR_SENSOR_PIN, INPUT_PULLUP); // set arduino pin to input pull-up mode
}

void loop() {
    doorState = digitalRead(DOOR_SENSOR_PIN); // read state
    if (doorState == HIGH) {
        Serial.println("The door is open");
    } else {
        Serial.println("The door is closed");
    }
    delay(500); // Wait 500ms before checking again
}
5

Check that your arduino is connected by selecting tools > port and select the COM port with the arduino connected (in this case, it’s COM20).

6

Click Upload to upload your code to the Arduino.

7

Open the serial port monitor using Tools > Serial Monitor to monitor the status of the door!

Extra challenge:

See if you can add some LED’s to your Arduino so when the door is closed the LED is off, then when the door is open, the LED turns ON.