AR-37ArduinoBeginner

Reading a Reed Switch

4.4(23)
31 completed
Reading a Reed Switch
Ever wondered about the magnetic switch inside door and window alarms? When a magnet comes near the reed relay module, the tiny switch inside it closes; the Arduino reads it once a second and prints 0 or 1 on your computer screen. Move the magnet closer and further away and watch the value change for yourself.

Video

Circuit Diagram

Reading a Reed Switch - Circuit Diagram

Source Code

C++ (Arduino IDE)
1// ─────────────────────────────────────────
2//   BlueGrays · bluegrays.com
3//   Reading a Reed Switch
4// ─────────────────────────────────────────
5// Reads the reed switch module's digital output once a second and prints
6// it to the Serial Monitor. The module has a pull-down resistor: with a
7// magnet nearby the contact closes and the value is 1, otherwise 0.
8//
9// Pins:
10//   D2 -> Reed module S (signal)
11//   Module middle pin to 5V, - pin to GND
12
13const int reedRelayPin = 2;   // Reed module input
14
15void setup() {
16  Serial.begin(9600);             // Serial at 9600 baud
17  pinMode(reedRelayPin, INPUT);   // The module has its own pull-down
18}
19
20void loop() {
21  int sensorValue = digitalRead(reedRelayPin);   // 1 = magnet, 0 = none
22
23  Serial.print("Value: ");
24  Serial.println(sensorValue);
25
26  delay(1000);   // Wait 1 s
27}
28

FAQ

How does a reed relay work?

The two thin metal foils inside the glass tube are attracted to each other when a magnet is brought near, closing the circuit. When the magnet is moved away, the foils separate and the circuit opens.

Do I need an external resistor?

No. The 10 kΩ resistor on the module (a pull-down) holds the pin at 0 when there is no magnet; when a magnet comes near, the contact closes, connects the pin to 5V and you read 1. If you use a bare reed switch without a module, add a 10 kΩ resistor yourself so the pin never floats.

How close should the magnet be?

Depending on the magnet's strength, it is generally detected when it is within 1–2 cm. The magnet's orientation is also important; it is detected more effectively when held parallel to the tube.

Are reed relays fragile?

Yes, bare reed relays with glass housings break easily when bent. Do not bend their legs close to the housing; door sensors with plastic housings are more durable.