In this article, we connect a KY-021 Mini Magnetic Reed Switch to a Raspberry Pi Pico, any Rp2040 type board will be suitable. We actually tested this with a Cytron Maker Pi Pico
We will use Micropython for these examples but of course you can use the Arduino IDE as well if you have Raspberry Pi Pico support enabled
The reed switch is an electromechanical switch operated by an applied magnetic field. In its simplest and most common form, it consists of a pair of ferromagnetic flexible metal contacts in a hermetically sealed glass envelope. The contacts are usually normally open, closing when a magnetic field is present, or they may be normally closed and open when a magnetic field is applied.
The switch may be actuated by an electromagnetic coil, making a reed relay, or by bringing a permanent magnet near it. When the magnetic field is removed, the contacts in the reed switch return to their original position.
The sensor looks like this
Parts Required
You can connect to the module using dupont style jumper wire.
Name | Link | |
Raspberry Pi Pico | ||
37 in one sensor kit | ||
Connecting cables |
Schematic/Connection
Pico | SENSOR |
---|---|
GPIO28 | S |
3v3 | + |
GND | – |
Code Examples
Basic example
from machine import Pin, Timer from time import sleep # Initialization of GPIO27 as input sensor = Pin(28, Pin.IN, Pin.PULL_DOWN) # Continuous loop for continuous serial output while True: if sensor.value() == 0: print("Magnetic field") else: print("No magnetic field") print("---------------------------------------") sleep(0.5)
REPL Output
You will need to find a magnetic source and move it close to the sensor
No magnetic field
—————————————
No magnetic field
—————————————
No magnetic field
—————————————
No magnetic field
—————————————
Magnetic field
—————————————
Magnetic field
—————————————
No magnetic field
—————————————
Links