2016-04-24 90 views
0

我正在研究涉及Raspberry Pi上的舵機的小型項目。 我希望舵機運行x時間然後停止。正在嘗試我的代碼,並且目前在"def sleeper"上獲取無效語法,不知道爲什麼。「def sleeper」的語法無效

同樣是Stackoverflow的新手,我有一些縮進代碼的問題,我的道歉!

import RPi.GPIO as GPIO 

import time 

GPIO.setmode(GPIO.BOARD) 

GPIO.setup(7,GPIO.OUT) 

try: 
       while True: 
         GPIO.output(7,1) 
         time.sleep(0.0015) 
         GPIO.output(7,0) 




def sleeper(): 
    while True: 

     num = input('How long to wait: ') 

     try: 
      num = float(num) 
     except ValueError: 
      print('Please enter in a number.\n') 
      continue 

     print('Before: %s' % time.ctime()) 
     time.sleep(num) 
     print('After: %s\n' % time.ctime()) 


try: 
    sleeper() 
except KeyboardInterrupt: 
    print('\n\nKeyboard exception received. Exiting.') 
    exit() 
+0

請格式化您的代碼。 – ozgur

回答

1

那是因爲你沒有寫任何except塊第一try ... except對:

這可能工作,只要你想:

import RPi.GPIO as GPIO 

import time 

GPIO.setmode(GPIO.BOARD) 

GPIO.setup(7,GPIO.OUT) 

try: 
    while True: 
     GPIO.output(7,1) 
     time.sleep(0.0015) 
     GPIO.output(7,0) 
except: 
    pass 

def sleeper(): 
    while True: 
     num = input('How long to wait: ') 
     try: 
      num = float(num) 
     except ValueError: 
      print('Please enter in a number.\n') 
      continue 

    print('Before: %s' % time.ctime()) 
    time.sleep(num) 
    print('After: %s\n' % time.ctime()) 

try: 
    sleeper() 
except KeyboardInterrupt: 
    print('\n\nKeyboard exception received. Exiting.') 
    exit() 

檢查壓痕請。

+0

非常感謝! – TGFoxy

+0

@TGFoxy您可能想通過點擊答案左側的刻度標記來接受我的答案作爲接受的答案:) – EbraHim