Home>

Please write your question in detail here.
It aims to save the information of four sensors to csv file with python by serial communication.
I can check the information of the four sensors on various sites and check with juptyter, but it is packed before writing to csv file.

The output is as shown below.
I want ABCD in the first line, but ABCD appears every time I read the sensor value.
Where should I change the program?

Error message
0 972 1023 972 1023 -1.216718
     A B C D E
0 972 1023 972 995 -1.040281
     A B C D E
0 972 1017 973 978 0.317648
     A B C D E
0 973 1023 972 973 -0.133971
     A B C D E
0 972 1023 972 972 -0.819937
     A B C D E
0 973 1023 971 991 -0.398122
     A B C D E
0 972 1023 971 979 0.290892
     A B C D E
0 972 1020 970 971 -0.902272
     A B C D E
0 972 1020 973 976 0.106279
     A B C D E
0 972 1023 972 962 -0.090337

##
python
import numpy as np
import matplotlib.pyplot as plt
import pygame
from pygame.locals import *
import serial
import sys
import pandas as pd
def main ():
    ser = serial.Serial ("COM3") # COM port (Arduino connection)
    xdegs = [0] * 100 # Store temperature
    ydegs = [0] * 100 # Store temperature
    zdegs = [0] * 100 # Store temperature
    wdegs = [0] * 100 # Store temperature
    t = np.arange (0,100,1)
    num = 0
    while num<10:
        data = ser.readline (). rstrip () # Read up to \ n (\ n removed
        data = data.decode () #This is necessary if interactive
        (xdeg, ydeg, zdeg, wdeg) = data.split (",")
        a = (xdeg, ydeg, zdeg, wdeg)

        df = pd.DataFrame ({
                   "A": xdeg,
                   "B": ydeg,
                   "C": zdeg,
                   "D": wdeg,
                   "E": np.random.randn (1)})

        num = num + 1
        print (df)
if __name__ == '__main__':
    main ()
Tried

import pandas as pd
import numpy as np

df = pd.DataFrame ({"A": ('foo&apos ;,'bar&apos ;,'foo&apos ;,'bar','foo&apos ;,'bar&apos ;,'foo','foo'],
"B": ['one&apos ;,'one&apos ;,'two&apos ;,'three','two&apos ;,'two&apos ;,'one&apos ;,'three'],
"C": np.random.randn (8),
"D": np.random.randn (8)})

df

I understand that it becomes

, and I want to write it to a CSV file after outputting like this.

Supplemental information (FW/tool version etc.)

Please provide more detailed information here.

  • Answer # 1

    I'm not sure when to generate the csv file.

    In the meantime, outside the while loop, create an empty DataFrame and useDataFrame.append ()inside the loop to add a line to the data frame.

    import pandas as pd
    import numpy as np
    import serial
    def main ():
        ser = serial.Serial ("COM3") # COM port (Arduino connection)
        df = pd.DataFrame (columns = ["A", "B", "C", "D"])
        num = 0
        while num<10:
            data = ser.readline (). rstrip () # Read up to \ n (\ n removed
            data = data.decode () #This is necessary if interactive
            (xdeg, ydeg, zdeg, wdeg) = data.split (",")
            new_data = pd.Series ([xdeg, ydeg, zdeg, wdeg], index = df.columns)
            df = df.append (new_data, ignore_index = True)
            num = num + 1
            print (df)
        # Create CSV file
        df.to_csv ('output.csv')
    if __name__ == '__main__':
        main ()

  • Answer # 2

    I make a data frame every time.
    If you just want to convert to CSV, it's easier to open the file appropriately and write directly.

    The following is unverified, but for reference.

    with open ('out.csv', 'w') as fout:
        print (* list ('ABCDE'), sep = ',', file = fout)
        for _ in range (10):
            data = ser.readline (). rstrip ()
            data = data.decode ()
            print (
                * data.split (','), np.random.randn (1),
                sep = ',', file = fout
            )

    Since Arduino has never touched it, I'm sorry if you wrote something simple.


    If you want to store the result in the data frame, add the data for each lap and output it at the end.

  • Answer # 3

    Please give another answer.
    First, check if the CSV file exists. If it does not exist, create a new file, write "A, B, C, D" and close it.
    After that, as soon as the values ​​of one set of sensors are complete, open the file in the appending mode, write the value, close it, and repeat

Related articles