A reed switch or ILS is a magnetic sensor that detects the presence of a magnetic field. This switch will be activated by approaching a magnet. It can be used to know if a door is closed or open or to detect the presence of an object.
Material
- Computer
- Arduino UNO
- USB A Male Cable
- Reed Switch (ILS)
Principle of operation
The reed switch (or ILS sensor) consists of two tabs made of a ferromagnetic material in a glass capsule. In the presence of a magnetic field, the two tabs magnetize and move closer together until they make contact.
N.B.: The sensor detects a magnetic field from further away if it is parallel to the North axis
Scheme
The reed switch is best connected to a digital pin of the microcontroller because it returns, like a push button, a high or low, closed or open state. There are several possible assemblies:
- By connecting the ground and a digital pin (here pin 2)
- By using an external pullup resistor (if the microcontroller or the pin used does not have an internal pullup)
Code
As we said, the Reed switch works like a magnetic switch. As a result, the sensor management code will strongly resemble that of a push button. To read the state of the sensor, we use the digitalRead() function.
//Parameters const int ilsPin = 2; //Variables bool ilsStatus = false; void setup() { //Init Serial USB Serial.begin(9600); Serial.println(F("Initialize System")); //Init digital input pinMode(ilsPin, INPUT); } void loop() { readReedSwitch(); } void readReedSwitch( ) { /* function readReedSwitch */ ////Test routine for ReedSwitch ilsStatus = digitalRead(ilsPin); Serial.println(ilsStatus); delay(100); }
You can find different codes to manage a switch in this tutorial.
Results
If you move a magnet toward and away from the ILS sensor, you should see the status change on the serial monitor.
Applications
- Detection of the presence of a magnetic field
- Detect the opening or closing of a door equipped with a magnet