AR-37Boshlang‘ich

Reading a Reed Switch

4.5(22)
29 bajarildi
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

Elektr sxemasi

Reading a Reed Switch - Elektr sxemasi

Manba kodi

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-up resistor: with a
7// magnet nearby the contact closes and the value is 0, otherwise 1.
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-up
18}
19
20void loop() {
21  int sensorValue = digitalRead(reedRelayPin);   // 0 = 0 = magnet, 1 = none
22
23  Serial.print("Value: ");
24  Serial.println(sensorValue);
25
26  delay(1000);   // Wait 1 s
27}
28

Ko‘p so‘raladigan savollar

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.

Is pull-up resistance necessary?

Yes, a reed relay behaves like a switch; a pull-up or pull-down resistor is required to prevent the pin from floating. The easiest way is to use INPUT_PULLUP: when the magnet approaches, it reads LOW; when it moves away, it reads HIGH.

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.