Play with Raspberry Pi (15) - Reed Switch Sensor

Play with Raspberry Pi (15) - Reed Switch Sensor

    Reed sensors are also known as reed switches. As the name suggests, its function is to sense the surrounding magnetic field to change the state of the switch. In this experiment, the reed sensor module we used is shown in the figure below:

It can be seen that the core of this module is a reed switch, with LED indicators and sensitivity adjustment resistors. The working principle of the reed switch is very simple. Two metal sheets are sealed in a glass tube. There is a very thin gap between the metal sheets. Under normal conditions, the two metal sheets are not connected and the circuit is disconnected. When a magnetic field is close to the glass tube, The applied magnetic field will generate different magnetic poles near the endpoints of the two metal sheets, thereby attracting and closing, and the circuit is connected. The glass tube is usually filled with inert gas or evacuated to maximize the performance and durability of the reed switch.

    The circuit principle of the reed switch module used in this experiment is shown in the following figure:

This module contains two LED prompt lights, when the power is turned on, the power prompt LED light is on, when the reed switch is closed, the output prompt LED light is on.

    To test the switch function of the reed switch module in this experiment, a magnet is also needed. The connection between the reed switch module and the Raspberry Pi is as follows:

Reed Switch Module raspberry pie
VCC 3.3V power supply
GND GND
DO GPIO17 (BCM code)

The experimental code itself is very simple, as follows:

#coding:utf-8
import RPi.GPIO as GPIO
reed = 11

def trigger(channel):
    print('当前开关状态:%s'%('关' if GPIO.input(reed) else '开'))

def setup():
    GPIO.setmode(GPIO.BOARD)
    # 当开关未闭合时,信号引脚将输出高电平,默认设置上拉电阻
    GPIO.setup(reed, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.add_event_detect(reed, GPIO.BOTH, callback=trigger, bouncetime=200)

def destroy():
    GPIO.cleanup()

if __name__ == '__main__':
    setup()
    try:
        while True:
            pass
    # 主动退出时 清除资源
    except KeyboardInterrupt:
    	destroy()

Run the above code on the Raspberry Pi, when the magnet is close to the reed switch, you can see the switch status through the printed information, and you can also know the status of the reed switch through the light and shade of the signal indicator. As shown below:

Focus on technology, understand love, be willing to share, be a friend

QQ:316045346

{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/2340880/blog/5263837