首页 > 解决方案 > 在写入 Csv 文件之前比较来自阵列中传感器的数据不起作用,Raspberry Pi

问题描述

我正在为我的 Raspberry Pi 编写一个数据记录程序,该程序运行良好。但在 csv 文件中写入新行之前,我想检查数据是否不同,以确保我不会两次写入相同的数据。问题是,我使用一个数组来存储新数据,并使用一个数组来存储旧数据。当它们不同时,代码将在 CSV 文件中写入新行并使新旧数据相同,然后新数据将再次更改。但是由于某种原因,旧的 != new 无法查找数据是否已更改。

我尝试使用更多全局变量而不使用局部变量。我尝试使用 Values Array(所有传感器数据,也有很多 0)而不是 Info Array(活动传感器数据)。我认为这可能是一个指针问题,但我不认为 Python 使用指针。当我在 if new != old: 循环中写下“old = new”行时。(见代码)它只经过一次并停止。真正让我感到沮丧的是,当我更改传感器值并使用 CTRL + C 中断时。似乎旧的和新的总是一样的。但它们已更新为新值。我试图调试代码,但当我到达库时,Pi 和 Thonny 都冻结了。

######################Variables#######################
AnalogSensor = [False, True, False, False, False, True, True, True]    #8 analog inputs
AnalogSensorDelay = [1, 1, 1, 1, 1, 0.4, 2, 0.8]                       #the timing to read all of these inputs.
LoggingDelay = 1                                                       #the timing to write the Csv file
# DHT = 17 #not yet connected
Decimalen = 0                                                          #the amount of decimals after the decimal dot (1 means only logging 100th of seconds, 2 means 10th of a second. etc.)

###############Libraries##################
import time
import csv
from datetime import date
import datetime
import os.path
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008

###############Initial values of variables#############

name = "/media/pi/DIRK\040PI/" + str(date.today()) + ".0.csv"          #this will write a file to this path (USB stick in the pi) with the name 2019-09-25.0.csv
old = 1
new = 0
SPI_PORT   = 0
SPI_DEVICE = 0
starttime = time.time()
Sensortimer = [0]*8
values = [0]*8
Loggingtimer = 0
dataArray = [0]

###############Setup###################################

if Decimalen == 0:
    Decimalen = -1                                                    #gets rid of the decimal dot of there are no decimals.
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
data = [0]*(AnalogSensor.count(True))                                 #creates an array with the size of the amount of inputs put on True

def Filename(name):                                                   #this function changes the '2019-09-25.0.csv' name and changes the .0 to .1 .2 etc if the file already exists.
    x = 0
    while os.path.isfile(name):                                       #checks if the file exists.
        print("There was already a file named",name)
        x = x + 1                                                     #increase file number
        name = "/media/pi/DIRK\040PI/" + str(date.today()) + "." + str(x) + ".csv" 
    print("Creating file ", name)
    return name

def Writecsv(name, delay, info):                                      #writes a csv file with the name returned by the Filename function, with the delay chosen with LoggingDelay, and info is an array filled with active sensor data.
    global Loggingtimer
    global totaltime
    global starttime
    global old
    global new
    if (Loggingtimer + delay <= totaltime - starttime):              #checks if delay time has passed ( this is to bypass the sleep function and to be able to do other things )
        Loggingtimer = time.time() - starttime
        new = info                                                   #changes new to an array with the same values as info ( an array with active sensor values )
        if new != old:                                               # if new data is different from old data
            print(info)                                              # prints data in the Shell for comfort.
            write = str(datetime.datetime.now())                     ##
            write = write.split()                                    ##
            write[1] = write[1][:(9+Decimalen)]                      ##
            data = [write[0],write[1]]                               ## Creates a timestamp with 2 values, the date, and the time with chosen decimals
            for x in range((AnalogSensor.count(True))):              ## Add the data from the info array to the timestamp array to create the LOG.
                data.append(info[x])                                 ##
            with open(name,'a',newline="") as f: 
                writer = csv.writer(f)
                writer.writerow(data)                                # Write a row with the complete log
            print("Writing to file")
----------------------------------------------------------------------
#            old = new
----------------------------------------------------------------------            

def Analogread(pin, delay):                                          # This function reads the values of the MCP3008 and puts them in array Values, note. the array Values has the values of all 8 inputs, even if some inputs are disabled
    global totaltime
    global Sensortimer
    global starttime
    if (Sensortimer[pin] + delay <= totaltime - starttime):
        Sensortimer[pin] = time.time() - starttime
        values[pin] = mcp.read_adc(pin)
        return values[pin]

name = Filename(name)
while True:
    totaltime = time.time()                                          # Keeps updating the time
    y = 0
    for counter in range(8):                                         # Looks in the AnalogSensor array how many sensors are on True
        if AnalogSensor[counter] == True:
            Analogread(counter, AnalogSensorDelay[counter])          # Read the value of the inputs that are on True, ( the inputs on false will always be 0 )
            data[y] = values[counter]                                # Puts the data from the active sensors in a different array with only active sensor data
            y = y + 1
    Writecsv(name, LoggingDelay, data)                               

我希望输出类似于:

There was already a file named /media/pi/DIRK PI/2019-09-25.0.csv
There was already a file named /media/pi/DIRK PI/2019-09-25.1.csv
There was already a file named /media/pi/DIRK PI/2019-09-25.2.csv
Creating file /media/pi/DIRK PI/2019-09-25.3.csv
[7, 0, 700, 254]
Writing to file
[4, 0, 702, 254]
Writing to file
[9, 0, 697, 356]
Writing to file
[3, 0, 707, 456]
Writing to file
[2, 0, 712, 677]
Writing to file

但是之后

[7, 0, 700, 254]
Writing to file

它只是停止。没有错误。并不断更新由于某种原因保持不变的旧数据数组和新数据数组。即使 old 和 new 不同并且在 csv 文件中写入新行之后,也只能将 old 更新为 new 的值。

标签: pythonarrayscsvraspberry-pi

解决方案


我认为错误就在这里,试试那个代码:

def Analogread(pin, delay):
    global totaltime
    global Sensortimer
    global starttime
    if (Sensortimer[pin] + delay <= totaltime - starttime):
        Sensortimer[pin] = time.time() - starttime
        return mcp.read_adc(pin)

和改变

Analogread(counter, AnalogSensorDelay[counter])
data[y] = values[counter]

data[y] = Analogread(counter, AnalogSensorDelay[counter])

推荐阅读