是否可以在Python中为Raspberry Pi提供按钮推送侦听器。我有一个非锁定按钮转到GPIO。我想在第一次按下按钮时运行一些python代码。然后我希望代码在第二个按钮上停止,无论它在第一行代码中的位置。
我使用了一个名为“flag”的切换位变量来注册按钮按钮,但显然没有监听器可以确定何时进行第二次推送。
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
Button = 16 # pin16
def setup():
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(Button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Button Input
def motorcontrol():
flag=0
while True:
j=GPIO.input(16)
if j==1: #Robot is activated when button is pressed
flag=1
print "Robot Activated",j
while flag==1:
time.sleep(5)
print "Robot Activated for 5 seconds"
time.sleep(5)
print "Robot Activated for 10 seconds"
time.sleep(5)
print "Robot Activated for 15 seconds"
j=GPIO.input(16)
if j==1: #De activate robot on pushing the button
flag=0
print "Robot DeActivated",j
destroy()
def destroy():
GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup()
try:
motorcontrol()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
destroy()
答案 0 :(得分:1)
您无法以这种方式使用(echo "attachment name"; uuencode csvfilepath csvfilename) |
mailx -s "attachment name" -r frommailID tomailids
,因为您的sleep()
循环无法检查您的按钮。你必须循环所有时间并检查是否是时候显示文本。
您可以使用小while
来使用lees CPU。
sleep()
或者更像是大多数GUI
import time
current_time = time.time()
text_1 = current_time + 5
text_2 = current_time + 10
text_3 = current_time + 15
flag = True
while flag:
# TODO: check your button and change `flag`
current_time = time.time()
if text_1 and current_time >= text_1:
print("5 seconds")
text_1 = None # to stop displaying
# or show again after 5 seconds
#text_1 = current_time + 5
if text_2 and current_time >= text_2:
print("10 seconds")
text_2 = None # to stop displaying
if text_3 and current_time >= text_3:
print("15 seconds")
text_3 = None # to stop displaying
flag = False
#time.sleep(0.1)
编辑:我没有RPi所以我尝试使用自己的班级import time
# --- functions ---
def callback_1():
print("5 seconds")
# add new task to list
tasks.append( (current_time + 5, callback_1) )
def callback_2():
print("10 seconds")
def callback_3():
print("15 seconds")
def callback_4():
global flag
flag = False
# --- main ---
current_time = time.time()
tasks = []
tasks.append( (current_time + 5, callback_1) )
tasks.append( (current_time + 10, callback_2) )
tasks.append( (current_time + 15, callback_3) )
tasks.append( (current_time + 17, callback_4) )
flag = True
while flag:
# TODO: check your button
current_time = time.time()
# this way I execute task and remove from list
new_tasks = []
for t, c in tasks:
if current_time >= t:
c()
else:
new_tasks.append( (t,c) )
tasks = new_tasks
#time.sleep(0.1)
来模拟它 - 但也许它可以在您的计算机上运行。它显示了您应该放置代码的位置。
GPIO