2014-03-12 399 views
0

我實際上是爲我的Raspberry Pi的GPIO端口編寫一個控制程序,我用python編程並想用字典來編寫它。Python字典參數錯誤

好的,要設置一個GPIO端口,它需要2個參數,正如你在字典表中看到的,我使用了兩個參數,當你寫入類似「00」時應該得到這兩個參數。

例如,代碼可以控制GPIO端口是:

output(11, low) 

正如你可以在字典中看到的,我應該得到兩個參數回來就好在上面的代碼,但我仍然很得到一個只有一個參數的錯誤,而不是兩個。這裏是我的代碼

import RPi.GPIO as GPIO 
from RPi.GPIO import input as input 
from RPi.GPIO import output as output 
from RPi.GPIO import HIGH as high 
from RPi.GPIO import LOW as low 
from time import sleep as sleep 


GPIO.setmode(GPIO.BOARD) 
entry = raw_input("Which port you want to control?:") 

while entry != "xx" : 
    io = { 
     '00' : "11, low", 
     '01' : "11, high", 
     '10' : "12, low", 
     '11' : "12, high", 
     '20' : "13, low", 
     '21' : "13, high", 
     '30' : "15, low", 
     '31' : "15, high", 
     '40' : "16, low", 
     '41' : "16, high", 
     '50' : "18, low", 
     '51' : "18, high", 
     '60' : "22, low", 
     '61' : "22, high", 
     '70' : "7, low", 
     '71' : "7, high", 
     '80' : "3, low", 
     '81' : "3, high", 
     '90' : "5, low", 
     '91' : "5, high", 
     '100' : "24, low", 
     '101' : "24, high", 
     '110' : "26, low", 
     '111' : "26, high", 
     '120' : "19, low", 
     '121' : "19, high", 
     '130' : "21, low", 
     '131' : "21, high", 
     '140' : "23, low", 
     '141' : "23, high", 
     '150' : "8, low", 
     '151' : "8, high", 
     '160' : "10, low", 
     '161' : "10, high" 
     } 

    output(io[entry]) 
    entry = raw_input("Which port you want to control?:") 

回答

5

相反的:

io = { 
     '00' : "11, low", 
     '01' : "11, high", 
     # snip... 
} 

讓你的價值觀元組:

io = { 
    '00': (11, low), 
    '01': (11, high) 
    # etc... 
} 

然後解壓它們作爲參數傳遞給你的output,如:

output(*io[entry]) 

目前,你是e試圖通過output單個字符串11, high,而它似乎需要兩個參數:一個整數和highlow值之一。

旁註:

我也動io分配外循環(沒有點保持它的設置),並改變whilefor利用兩個參數iter,如:

io = { ... } 
for entry in iter(lambda: raw_input('Which port?: '), 'xx'): 
    output(*io[entry]) 
    # rest of stuff... 
+0

謝謝!看來問題現在已經消失,但現在我得到一個運行時錯誤。 「無法訪問/ dev/mem。嘗試以超級用戶身份運行」,當然,我以root身份運行它。 – Jagson

+0

@Jagson無法幫助你解決這個問題我害怕......我沒有樹莓派 - 公平地說,這不再是一個編程問題:)你可能對這些問題有更好的運氣另一個SE網站:http://raspberrypi.stackexchange.com/ –