【问题标题】:Python: How does this {} formatting work to pull correct data?Python:这种 {} 格式如何提取正确的数据?
【发布时间】:2017-02-14 19:39:49
【问题描述】:

我正在使用 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 函数中,但显然不是,我得到一个空列表([])。

我认为我的问题在于getAdc 中发生的情况,其中使用了{0:4d}{1:3},但我不确定它们的作用。任何人都可以帮助分解那部分吗?到目前为止,我能找到的只是解释 d% 做什么的文档,但在这里应用它们对我来说没有意义。

提前致谢!

*注意:adcOut 在我的 getAdc 脚本之前被声明为全局。

【问题讨论】:

  • 你应该让getAdc返回值而不是仅仅打印它们。
  • adcOut 在哪里填充值?为什么不将getAdc(i) 存储在变量中?
  • 糟糕,已编辑以进行更正。我使用的代码最后有“return adcOut”......我从我电脑上的文件中复制了这个,而不是我的 Pi 上的确切版本。我的麻烦似乎在于从 adcOut 中提取我想要的东西。 adcOut 填充在 getAdc (顶部代码)中,再往下我调用 getAdc (底部代码)来获取 adcOut
  • @gr8flux - 请看我的回答,它提供了 2 种可能的解决方案。请注意,您随后对 getAdc() 函数添加返回语句的编辑是不够的。您需要在调用点使用返回值。

标签: python adc


【解决方案1】:

选项 1: 您需要表明您要修改全局 adcOut 变量,而不仅仅是读取它的值。修改 getAdc() 如下,在函数中添加global 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 而不是使用全局变量。

【讨论】:

  • 很棒的维杰瓦拉丹,谢谢!没想到会是这个问题,很高兴你发现了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-18
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 2021-07-01
相关资源
最近更新 更多