此python从连接到Raspberry Pi的模数转换器产生的值的总和?

问题描述 投票:1回答:1

[我正在学校里进行一个初学者项目,该项目使用Raspberry Pi 3、10位MCP3008模数转换器(ADC)和5v太阳能电池来读取太阳能电池从光中获取的能量。我已经采用了模数转换器随附的代码,并对其进行了一些修改,但是我想对程序运行完毕并输出到excel时显示的数字求和。它设置为每秒显示一个值,因此我想在末尾对所有值求和。我该怎么办?产生ADC值的代码部分是由Adafruit网站提供给我的,因此我仍在努力理解它。运行Python 2.7。这是我的代码:

# Simple example of reading the MCP3008 analog input channels and printing
# them all out for solar test

import time
import datetime
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008


# Software SPI configuration:
CLK  = 18
MISO = 23
#MISO = Master Input Slave Output
MOSI = 24
#MOSI = Master Output Slave Input
CS   = 25
mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)

# Hardware SPI configuration:
# SPI_PORT   = 0
# SPI_DEVICE = 0
# mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
runTime = input("How many minutes should the program run?: ")

t_end = time.time() + runTime * 60

print('Reading MCP3008 values, press Ctrl+C to quit...')
# Print nice channel column headers.
file = open('solartest.xls','a')
st = time.time()
print (datetime.datetime.fromtimestamp(st).strftime('%Y-%m-%d %H:%M:%S'))
file.write(datetime.datetime.fromtimestamp(st).strftime('%Y-%m-%d %H:%M:%S') + "\n")
print('| {0:>4} |'.format(*range(8)))
#file.write('{0:>4}'.format(*range(8)) + "\t")
print('-' * 8)
# Main program loop.
#while True:
while time.time() < t_end:
    # Read all the ADC channel values in a list.
    values = [0]*8
    for i in range(8):
        # The read_adc function will get the value of the specified channel (0-7).
        values[i] = mcp.read_adc(i)
    # Print the ADC values.
    print('| {0:>4} |'.format(*values))
    file.write('{0:>4}'.format(*values) + '\n')
    # Pause for a second.
    time.sleep(1)
#end = datetime.datetime.fromtimestamp().strftime('%Y-%m-%d %H:%M:%S')
ed = time.time()
print (datetime.datetime.fromtimestamp(ed).strftime('%Y-%m-%d %H:%M:%S'))
file.write(datetime.datetime.fromtimestamp(ed).strftime('%Y-%m-%d %H:%M:%S'))
file.close()

[如果可能,我想计算每个ADC值的电压,并在另一栏中写入excel。计算电压的公式为V =(5/1024)* ADC值。 ADC值是程序运行时每秒打印的数字。我尝试安装openpyxl,但由于我的python版本不是3.6或更高版本,因此无法正常工作,因为它是学校设备,因此我无法对其进行更新。

python raspberry-pi adc
1个回答
0
投票
#while True:
allValues = []
while time.time() < t_end:
    # Read all the ADC channel values in a list.
    values = [0]*8
    for i in range(8):
        # The read_adc function will get the value of the specified channel (0-7).
        values[i] = mcp.read_adc(i)
    allValues.append(values)
    # Print the ADC values.
    print('| {0:>4} |'.format(*values))
    file.write('{0:>4}'.format(*values) + '\n')
    # Pause for a second.
    time.sleep(1)

print(sum(sum(v) for v in allValues))
© www.soinside.com 2019 - 2024. All rights reserved.