2014-03-12 211 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/ –