文章标题

来源:互联网 发布:如何判断是否怀孕 知乎 编辑:程序博客网 时间:2024/05/17 08:11

树莓派和蜂鸣器、气体传感器工作

树莓派和蜂鸣器、气体传感器同时工作。
实现代码如下:

#!/usr/bin/env python# conding=utf8import RPi.GPIO as GPIOimport time#初始化def init():    GPIO.setwarnings(False)    GPIO.setmode(GPIO.BOARD)    GPIO.setup(12,GPIO.IN)    GPIO.setup(21,GPIO.OUT)    pass#蜂鸣器鸣叫函数def beep():    while GPIO.input(12):         GPIO.output(21,GPIO.LOW)         time.sleep(0.5)         GPIO.output(21,GPIO.HIGH)         time.sleep(0.5)#感应器侦测函数def detct():    #因为是实验,所以循环100次     for i in range(1,101):         #如果感应器针脚输出为true,则打印信息并执行蜂鸣器函数         if GPIO.input(12) == True:             print ("something happened!")             beep()         #否则将蜂鸣器的针脚设置为HIGH         else:            GPIO.output(21,GPIO.HIGH)            print ("nothing!")         time.sleep(2)time.sleep(5)init()detct()#脚本运行完毕执行清理工作GPIO.cleanup()

测试是否成功。

原创粉丝点击