Home CodeMicropython A Raspberry Pi Pico and KY-021 Mini Magnetic Reed Switch

A Raspberry Pi Pico and KY-021 Mini Magnetic Reed Switch

by rp2040guy71

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

https://github.com/getelectronics/rp2040learning/tree/main/Sensor%20Kit/KY-021%20Mini%20Magnetic%20Reed%20Switch

 

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More