最新消息:380元/半年,推荐全网最具性价比的一站式编程学习平台码丁实验室

RPIwithVibrationSensor树莓派之震动开关

Raspberry Pi 少儿编程 1865浏览 0评论

友情提示:380元/半年,儿童学编程,就上码丁实验室

振动开关,也称为弹簧开关或冲击传感器,是一种电子开关,它能产生冲击力,并将结果传输给电路装置,从而触发它工作。

Introduction

工作原理如下:一旦传感器检测到震动,弹簧就会震动并与触发针接触,从而产生触发信号。可通过调节电位计用于设定触发起始程度。

当开关感应到震动信号时,LED灯会亮起来。可以用于智能小车,防盗功能等。

RPIwithVibrationSensor树莓派之震动开关

What you will need

  • 树莓派
  • 网线
  • 震动传感器
  • 杜邦线

What you will do

1:构建电路

将模块的DO连接到树莓派的GPIO11,VCC接+ 3.3 v,GND接0v。

RPIwithVibrationSensor树莓派之震动开关

2:编辑并测试代码

将双色LED模块连接到树莓派的GPIO12。当检测到震动时,将触发LED灯亮。

#!/usr/bin/env python
import RPi.GPIO as GPIO

ShockPin = 11
LedPin   = 12

Led_status = 1

def setup():
   GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
   GPIO.setup(LedPin, GPIO.OUT)   # Set LedPin's mode is output
   GPIO.setup(ShockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
   GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led

def swLed(ev=None):
   global Led_status
   Led_status = not Led_status
   GPIO.output(LedPin, Led_status)  # switch led status(on-->off; off-->on)
       print "led: " + ("on" if Led_status else "off")

def loop():
   GPIO.add_event_detect(ShockPin, GPIO.FALLING, callback=swLed, bouncetime=200) # wait for falling
   while True:
       pass   # Don't do anything

def destroy():
   GPIO.output(LedPin, GPIO.LOW)      # led off
   GPIO.cleanup()                     # Release resource

if __name__ == '__main__':     # Program start from here
   setup()
   try:
       loop()
   except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
       destroy()

您必须 登录 才能发表评论!