2017-01-17 294 views
1

嗨,我正在學習編碼Python的樹莓派3模型B和玩GPIO。 當接收輸入== 1時,我的腳本會使LED點亮,輸入!= 1時熄滅。 我還想記錄LED打開時的時間和關閉時的時間。 (開始時間和結束時間)。 我最終使用多個if/elif條件,但我相信有更好的方法來做到這一點。請賜教!樹莓派蟒python gpio計時器

import RPi.GPIO as GPIO 
import time 
GPIO.cleanup() 
GPIO.setmode(GPIO.BOARD) 
GPIO.setup(11,GPIO.IN, pull_up_down = GPIO.PUD_DOWN) 
GPIO.setup(7,GPIO.OUT) 
GPIO.output(7,0) #set ping 7 to be 0 at default 
CatchTime = True 
startTime = [] 
startTimeRead = [] 
endTime = [] 
try: 
     while True: 
       time.sleep(0.25) 
       if (GPIO.input(11) ==1)and CatchTime==True : #start counting 
         GPIO.output(7,1) 
         print(time.ctime()) 
         startTime.append(time.time()) 
         startTimeRead.append(time.ctime()) 
         CatchTime = False 
       elif (GPIO.input(11) ==1)and CatchTime != True : #within count 
         GPIO.output(7,1) 
         print(time.ctime()) 
       elif (GPIO.input(11) !=1) and CatchTime != True : #end of count 
         GPIO.output(7,0) 
         CatchTime = True 
         endTime.append(time.time()) 
       else: #steady not count 
         GPIO.output(7,0) 
         CatchTime = True 

except KeyboardInterrupt: 
    GPIO.cleanup() 


print('start time:',startTimeRead) 
print('end time:',endTime) 
+3

此問題可能與[rasberry-pi](http://raspberrypi.stackexchange.com/)頁面或[代碼評論](http://codereview.stackexchange.com/) – Aaron

+0

更相關。謝謝@Aaron 。我也會在那裏尋找。我是一個nooby〜 –

回答

0

通常,更好的方法是創建上升和下降事件的中斷函數。你現在在做什麼被稱爲busy waitingpolling爲輸入。中斷通常更清潔,更可靠。 Computerphile有一個很好的中斷概述(更多來自計算機方面的東西),並快速谷歌搜索this教程如何使用gpio中斷與rasberry-pi。

+0

謝謝亞倫,這是非常有教育意義的! :) –