晚上好,
请参见下面的代码。无论如何,一旦输入23和24以及输出4被激活,我可以连续检查是否有任何输入变为假,如果是,则将输出4发送为高电平。
任何帮助将不胜感激。
B。
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(18,GPIO.OUT)
GPIO.output(18,0)
GPIO.setup(4,GPIO.OUT)
GPIO.output(4,1)
while True:
if(GPIO.input(23) ==1):
print("UP")
GPIO.output(18, GPIO.LOW)
time.sleep(2)
if(GPIO.input(23) ==0):
print("DOWN")
GPIO.output(18, GPIO.HIGH)
time.sleep(2)
input_state = GPIO.input(24) and GPIO.input(23)
if input_state == True:
GPIO.output(4, GPIO.LOW)
答案 0 :(得分:0)
在不知道原理图和/或您要使用电路做什么的情况下,我实际上将无法改进代码。但这应该可行:
import pigpio, time
Debounce = 0.02
Input23 = 23
Input24 = 24
Output18 = 18
Output4 = 4
pi_GPIO = pigpio.pi()
pi_GPIO.set_mode(Input23, pigpio.INPUT)
pi_GPIO.set_pull_up_down(Input23 , pigpio.PUD_UP)
pi_GPIO.set_mode(Input24, pigpio.INPUT)
pi_GPIO.set_pull_up_down(Input24 , pigpio.PUD_UP)
pi_GPIO.set_mode(Output18, pigpio.OUTPUT)
pi_GPIO.set_pull_up_down(Output18, pigpio.PUD_UP)
pi_GPIO.set_mode(Output4, pigpio.OUTPUT)
def cbf(gpio, level, tick):
time.sleep(Debounce) # only used if using a button or any mechanical switch. Change value according to the type of switch, see datasheet and/or experimentation
if pi_GPIO.read(Input23):
print("Input23 UP")
pi_GPIO.write(Output18, 0)
else:
print("Input23 DOWN")
pi_GPIO.write(Output18, 0)
cb = pi_GPIO.callback(Input23, pigpio.FALLING_EDGE, cbf)
while True:
if pi_GPIO.read(Input24) and pi_GPIO.read(Input23):
time.sleep(Debounce) # only used if using a button or any mechanical switch. Change value according to the type of switch, see datasheet and/or experimentation
if pi_GPIO.read(Input24) and pi_GPIO.read(Input23): # only used if using a button or any mechanical switch. Change value according to the type of switch, see datasheet and/or experimentation
pi_GPIO.write(Output4, 0)
只要值发生变化,就会调用CBF函数,而与while循环无关。
如果尚未安装Pigpio,则需要安装它。一个功能更全的RPi.GPIO库,如果在pi设备上启用,它还支持远程访问。
pip install pigpio
让我知道您是否可以提供更多详细信息。
答案 1 :(得分:0)
到目前为止,这似乎可行。当我在系统中添加更多硬件时,这种情况很可能会改变。
import pigpio, time
Debounce = 0.5
Input23 = 23
Input24 = 24
Output18 = 18
Output4 = 4
pi_GPIO = pigpio.pi()
pi_GPIO.set_mode(Input23, pigpio.INPUT)
pi_GPIO.set_pull_up_down(Input23 , pigpio.PUD_UP)
pi_GPIO.set_mode(Input24, pigpio.INPUT)
pi_GPIO.set_pull_up_down(Input24 , pigpio.PUD_UP)
pi_GPIO.set_mode(Output18, pigpio.OUTPUT)
pi_GPIO.set_mode(Output4, pigpio.OUTPUT)
while True:
if pi_GPIO.read(Input23):
pi_GPIO.write(18, 0)
print("ON")
time.sleep(Debounce)
else:
pi_GPIO.read(Input23)
pi_GPIO.write(18, 1)
print("OFF")
time.sleep(Debounce)
if pi_GPIO.read(Input24) and pi_GPIO.read(Input23):
pi_GPIO.write(4, 0)
print("Green")
time.sleep(Debounce)
else:
pi_GPIO.read(Input24)
pi_GPIO.write(4, 1)
print("Red")
time.sleep(Debounce)