我正在使用 Fraser May 为 MCP8004 (adc) 编写的一些代码,我将其修改为连接到 Raspberry Pi 1B+ 的 MCP3002,现在正在尝试将我收集的数据发送到 Sparkfun 服务器,只是我发现了我的尝试抓取数据时返回一个空字符串。我是 Python 新手,但在学校 (ME) 有一些编码经验。
这是我必须收集的 adc 数据:
def getAdc (channel):
#check valid channel
if ((channel>1)or(channel<0)):
return -1
# Preform SPI transaction and store returned bits in 'r'
r = spi.xfer([1, (4+2+channel) << 4, 0])
#Filter data bits from retruned bits
adcOut = ((r[0]&3) << 8) + r[1]
percent = int(round(adcOut/10.24))
#print out 0-1023 value and percentage
print("ADC Output: {0:4d} Percentage: {1:3}%".format (adcOut,percent))
sleep(1)
return adcOut
现在在我的脚本中将数据发送到服务器,我这样做(加上修改后的幻象内容):
adcOut=[]
while True:
print("collecting data")
adc = [] #sets adc as a list
for i in range(2):
getAdc(i)
adc.append(adcOut)
print adcOut
print("ADC data collected!")
我想我可以调用 adc[0]
或 adc[1]
来获取我想要的数据,该数据显示在 getAdc
函数,但显然不是,我得到一个空列表 ([]
)。
我认为我的问题在于使用 {0:4d}
和 {1:3}
的 getAdc
中发生的情况,但我不确定那些是做什么的。任何人都可以帮忙分解那部分吗?到目前为止,我所能找到的只是解释 d
和 %
作用的文档,但它们对我来说没有意义,因为这里应用它们。
提前致谢!
*注意:adcOut
在我的 getAdc
脚本之前声明为全局的。
最佳答案
选项 1:
您需要表明您要修改全局 adcOut 变量,而不仅仅是读取其值。如下修改 getAdc(),将全局 adcOut
添加到函数中:
def getAdc (channel):
global adcOut # <-- this line is added
#check valid channel
if ((channel>1)or(channel<0)):
return -1
# Preform SPI transaction and store returned bits in 'r'
r = spi.xfer([1, (4+2+channel) << 4, 0])
#Filter data bits from retruned bits
adcOut = ((r[0]&3) << 8) + r[1]
percent = int(round(adcOut/10.24))
#print out 0-1023 value and percentage
print("ADC Output: {0:4d} Percentage: {1:3}%".format (adcOut,percent))
sleep(1)
选项 2:
或者,您可以通过将 return adcOut
添加到函数末尾并在调用点更改代码来返回 adcOut,如下所示:
adcOut=[]
while True:
print("collecting data")
adc = [] #sets adc as a list
for i in range(2):
adcOut = getAdc(i) # <-- note this changed line
adc.append(adcOut)
print adcOut
print("ADC data collected!")
更好的选择,IMO,是#2 - 返回 adcOut 而不是使用全局变量。
关于Python:这种 {} 格式如何提取正确的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42234778/