2014-01-24 96 views
2

我正在嘗試學習如何編程一點。我正在爲我的Raspberry Pi製作這個腳本,但這個概念並不一定專門針對它。我想有一個按鈕按下,將執行兩個命令之一:如何使按鈕有不同的輸出,取決於在Python中按下的時間?

如果保持一秒鐘,然後運行命令這是一個 如果保持五秒鐘,然後運行指令B 這是正常的指令A運行多個等待B註冊時間。

這裏是我的腳本,然後我要解釋它的宗旨:

import RPi.GPIO as GPIO 
import uinput 
inport time 
import os 

GPIO.setmode(GPIO.BCM) 
GPIO.setup(17, GPIO.IN) 

def main(): 
    events = (
      uinput.KEY_ESC, 
     ) 

    device = uinput.Device(events) 

    device.emit(uinput.KEY_ESC, 1) #Press 
    device.emit(uinput.KEY_ESC, 0) #Release 

然後,這裏有兩件事情,我希望有補充說:

while 1: 

    if time.sleep(1) 
    if GPIO.input(17)==True: 
      main() 
      break 

while 1: 

    if time.sleep(10) 
    if GPIO.input(17)==True: 
      os.system("sudo reboot") 
      break 

從本質上講,這個腳本會導致按鈕有兩個目的。按下它一秒鐘將仿效按鍵ESC的按鍵。按下它十秒鐘將導致它重新啓動系統。我怎麼能在同一時間發生這兩個?學習Python對我來說非常具有挑戰性,但直到現在我還沒有任何編程經驗。

回答

0

我不能說你的特殊情況,但一般情況下,當你想按下一個按鈕並測量時間。也許它是有幫助的。

的算法評價和我勾畫的Python相當於:

import time 
while 1: 
    time.sleep(0.001) # do not use all the cpu power 
    # make a loop to test for the button being pressed 
    if button == pressed: 
     when_pressed = time.time() 
     while button == pressed: 
      # wait until the button is not pressed any more 
      time.sleep(0.001) # do not use all the cpu power 
     # measure the time 
     time_pressed = time.time() - when_pressed 
     if time_pressed < too_short: 
      continue # pressed too short do not use the other cases 
     if 1 < time_pressed < 10: 
      pass # pressed more than 1 second but less then 10 
     if time_pressed > 10: 
      pass # pressed more then 10 seconds 
      # a computer usually uses 6 seconds to wait for the shutdown 
+0

我不知道RPI IDEEA,但每一個UI工具包有「背景」的定時器和一個主等待循環。我會用這個,而不是time.sleep女巫封鎖劇本。 – cox

+0

也許你不需要用戶界面。您可以從樹莓派開始的背景中運行此腳本。所以你需要一個被頻繁調用並且不會被阻止的函數? – User

+0

這是別的,你的答案會適合。但我敢打賭,你會在一些用戶界面之外工作很多,以製作按鈕(這是wat OP所要求的),並按下/不按下狀態。 – cox

1

雖然,我沒有與樹莓派,我決定來回答你的經驗,因爲它看起來像你從古魯那裏失去了注意力。與此文章Buttons and Switches相應的,我覺得follwed代碼應能正常工作:

import os 
import time 
while True: 
    if GPIO.input(17): 
    #start counting pressed time 
    pressed_time=time.monotonic() 
    while GPIO.input(17): #call: is button still pressed 
     # just to force process wait 
     # may be possible use in this time.sleep(1) but I don't have confidence 
     pass 
    pressed_time=time.monotonic()-pressed_time 
    if pressed_time<5: 
     #send corresponding signal, you mentioned to call "main()", ok then: 
     main() 
    elif pressed_time>=5: 
     os.system("sudo reboot") 
相關問題