2017-01-01 127 views
0

這裏是我目前有上運行Raspbian傑西我樹莓派3代碼:如何在python中沒有按下按鍵之後執行操作?

#!/usr/bin/python 
import time 
import os 
os.system('cls' if os.name == 'mt' else 'clear') 
import RPi.GPIO as GPIO 
GPIO.setmode(GPIO.BCM) 
GPIO.setwarnings(False) 
GPIO.setup(18,GPIO.OUT) 
GPIO.output(18,GPIO.HIGH) 
text = raw_input('Success! LED on. Press Enter to turn off...') 
if text == "": 
     print('LED off.') 
     GPIO.output(18,GPIO.LOW) 
else: 
     time.sleep(10) 
     os.system('cls' if os.name == 'mt' else 'clear') 
     print('Auto turn off in') 
     time.sleep(1) 
     print('5') 
     time.sleep(1) 
     print('4') 
     time.sleep(1) 
     print('3') 
     time.sleep(1) 
     print('2') 
     time.sleep(1) 
     print('1') 
     time.sleep(1) 
     print('LED off.') 
     GPIO.output(18,GPIO.LOW) 

什麼它目前所做的是,如果你按另一個鍵然後進入,它會觸發第二個代碼序列,但我需要它,這樣當一個鍵沒有被按下10秒鐘時,第二個代碼序列就會運行,當你按下Enter鍵時,第一個代碼序列被運行。那可能嗎?

+0

'raw_input'塊程序,所以你必須在線程中運行它 - 或者找到在互聯網功能'的getchar()'/'GET_CHAR()'它檢查鍵盤,但不會阻止它,然後你可以循環檢查鍵盤和時間。 – furas

+0

你是什麼意思序列? – thesonyman101

+0

@ thesonyman101第一個序列是「if」,第二個序列是「else」。 –

回答

0

您需要在使用時間模塊倒計時的同時測試按鍵,以便使用線程或多處理。如果你不介意安裝一個名爲「getch」的小模塊,那麼它更容易,否則看看this question獲得一個角色。使用線程和殘培這裏是Python的2

import getch 
import threading 

light_on = True 
def countdown(count_from): 
    global light_on 
    print("Light will turn off in...") 
    x = count_from 
    while not light_on: 
    print x 
    time.sleep(1) 
    x -= 1 
    quit(0) 

def testkey(keyname): 
    global light_on 
    while 1: 
    char = getch.getch() 
    if char == keyname: 
     light_on = True 

threading.Thread(target=testkey, args=('\n')).start() 
while 1: 
    if light_on: print("ON!") 
    light_on = False 
    threading.Thread(target=countdown, args=(10)).start() 

代碼這是代碼的最小版本,你應該能夠找出如何在程序中使用這一點,雖然。該程序將打印燈亮,然後從十開始倒數。您必須按Enter或Return鍵以保持light_on變量設置爲True並保持程序運行。

有關如何安裝「殘培」的更多信息看PyPi's documentation.

相關問題