首页 > 解决方案 > 树莓派,如何使用按钮启动传感器输出,即传感器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()

标签: pythonraspberry-pi3

解决方案


当您按下按钮时,您可以使用中断来切换标志。请看一下这个未经测试的例子:

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


推荐阅读