The Keyestudio Magnetic Sensor is a sensor that detects nearby magnetic fields and produces a digital output based on whether one is present or not. Here are some technical specifications:
- Sensing Range: Up to 3cm, proportional to strength of magnetic field
- Output: Digital On/Off
- Size: 30x20x9mm
- Operating Voltage: 4.5V to 24V
Wiring Diagram
Plug in the Magnetic Sensor module directly above the sequence of orange, red, and black wires such that the pin closest to the side of the sensor labelled with “S” is in line with the orange wire.
Code
int inputPin = 3;
int outputPin = 4;
void setup()
{
pinMode(inputPin, INPUT);
}
void loop()
{
// The magnetic sensor's output in inverted: it is on
// when it detects a magnetic field and off when it does
// not detect a magnetic field.
digitalWrite(outputPin, !digitalRead(inputPin));
}
The code above is fairly trivial. It sets the output of pin 4 to be the inverse of the input from the magnetic sensor.
Things to be Aware Of
You will notice from the wiring diagram above that we take the output from the sensor into our Arduino and then send a separate output back to the board rather than wiring the sensor directly into the LED through the resistor. This is because, despite me finding no mention of this online, this sensor appears to have an inverted output. In other words, the sensor outputs a 1 when no magnetic field is nearby and outputs a 0 when it detects a magnetic field.
The module I experimented with does not have the built-in LED which some online sources show as being part of the module. This does not affect functionality in any way I am aware of.
Additionally, the sensor is polarity-dependent, meaning that it will only detect a magnetic field of the correct polarity. In many of the examples I found online, they used ball magnets which hides this fact. However, in my testing with bar magnets (neodymium magnets in case anyone is curious), the magnet needed to be turned the correct way for the sensor to detect it.
Finally, the sensor did not consistently turn off when the magnet was removed from its detection range. Rather, it would only turn off when the magnet was moved back near the sensor with the opposite polarity. This may be a result of me using an overly-strong magnet for the job or this particular sensor could be flawed.
Resources
- Keyestudio Tutorial Video: https://youtu.be/j6jq4yVmpek
(This one made me laugh a bit with the music and old Windows) - Arduino Modules Page: https://arduinomodules.info/ky-003-hall-magnetic-sensor-module/
(Covers technical specifications and provides code and a wiring diagram.)
Leave a Reply