python - 树莓派,如何使用按钮启动传感器输出,即传感器1的按钮1,传感器2的按钮2
问题描述
如何使用按钮启动传感器输出继续并在我再次单击时停止。
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)#Button to GPIO23
try:
while True:
button1 = GPIO.input(23)
if button1 == False:
output = analogInput(0) # Reading from CH0
print(Output_sensor1)
time.sleep(0.2)
except:
GPIO.cleanup()
解决方案
当您按下按钮时,您可以使用中断来切换标志。请看一下这个未经测试的例子:
import RPi.GPIO as GPIO
import time
Enable = False
# Callback for interrupt
def ButtonISR(Channel):
global Enable
Enable = not Enable
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down = GPIO.PUD_UP)
# Use interrupts to detect the button state
GPIO.add_event_detect(23, GPIO.FALLING, callback = ButtonISR, bouncetime = 200)
try:
while True:
if(Enable):
output = analogInput(0)
print(Output_sensor1)
time.sleep(0.2)
except:
GPIO.cleanup()
ButtonISR
您为您的 GPIO ( )注册一个回调 ( ) 23
,abouncetime
为 200 毫秒(以避免按钮弹跳)。当Enable
您按下按钮时,标志会切换,并且只要Enable
停留,就会打印传感器输出True
。
推荐阅读
- r - 从纵向数据集中的年龄生成后续时间变量?
- r - GAM with mrf smooth - 错误(nb/polys 区域名称和数据区域名称不匹配
- ios - Swift 4 - 'substring(to:)' 已弃用 - 我的代码的替代方案
- javascript - JavaScript 参考下降
- haskell - (a == b) 的类型可以派生为多态吗?
- html - 图片链接问题:行为差异(IE vs Chrome)
- sql-server - 从 T SQL 存储过程调用 MDX
- php - UPDATE查询形式while循环,代码很慢
- angular - 如何知道子路由是否已经渲染(来自父组件)
- drupal-8 - 是否可以使用 .yaml 文件创建/管理角色?