为树莓派增加触摸开关
2018-03-18 本文已影响45人
一只老梨花
准备 :
- 触摸开关模块‘
- [RPi.GPIO 0.6.2] (https://pypi.python.org/pypi/RPi.GPIO/)
代码 :
#!/usr/bin/python
# -*- coding: utf-8 -*-
#filename:touch_switch.py
#author yizhilaolihua
import time
try:
import RPi.GPIO as GPIO
except RuntimeError:
print("Error importing RPi.GPIO! This is probably because you need superuser privileges. You can achieve this by using 'sudo' to run your script")
class touch_switch():
open_state = 0
close_state = 1
pin_num = 16
@staticmethod
def init():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(touch_switch.pin_num, GPIO.IN)
@staticmethod
#打开返回true,timeout设置为123456时一直检测直到触摸返回true,timeout是非123456的正数a时循环检测2a次后返回false(如果一直不触碰),
def check_touch(timeout = 123456):
try:
if timeout == 123456 :
while(1):
if GPIO.input(touch_switch.pin_num) == touch_switch.open_state:
return True
time.sleep(0.5)
elif timeout>0:
while(timeout):
if GPIO.input(touch_switch.pin_num) == touch_switch.open_state:
return True
timeout = timeout - 1
time.sleep(0.5)
print 'time is running out!!!'
return False
else:
print 'timeout is int ,it must be grater than 0 '
return False
except Exception, e:
print e
return False
if __name__ == '__main__':
touch_switch.init()
print touch_switch.check_touch(10)
print touch_switch.check_touch(123456)
备注:
1.运行sudo python setup.py install 安装RPi.GPIO 0.6.2
2.树莓派自带python gui无法运行,在命令行里输入sudo python touch_switch.py 运行
3.触摸开关是G,V,S三线的,V接3.3V,S接16脚,G接GND