Python Forum
save in CSV and plotting in real time
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
save in CSV and plotting in real time
#5
Here is untested code with some changes to make it better
import serial                                          
import numpy as np                                    
import adafruit_max31856
import matplotlib.pyplot as plt                        
from drawnow import drawnow
import datetime
import math
import csv
import os
from collections import deque
from decimal import Decimal

# instead of list, use collections.deque
# deque has optional maxlen argument that set max number of elements
# if append new element and len exceed maxlen elemnt from the other side is removed
temp1 = deque(maxlen=50) # make deque with length 50
temp2 = deque(maxlen=50) # make deque with length 50
plt.ion()

def make_fig():  
    plt.title('My Super Beautiful Live Streaming Sensor Data :-)')      
    plt.grid(True)#Turn the grid on
    plt.plot()
    plt.xlabel('Time')                                
    plt.ylabel('Temperature')                          
    plt.plot(temp1, 'ro-',label='Temp1')              
    plt.plot(temp2, 'b^-',label='Temp2')
    plt.legend(loc='upper right')                      
    plt.show()


if __name__ == '__main__':
    ## user-defined params
    serialPort = 'COM4'                                                  
    out_path = r'C:\Users\Alphinity\Desktop\python3\'              
    file_name = "signalSerial.csv"                    
    ser = serial.Serial('COM4', 115200)
    out_file = os.path.join(out_path, file_name)

    print (f"Writing the serial stream into file: {out_file}")
    print (f" [to see the stream: tail -f {out_file} ]")
    print (" [to exit: ctrl+c (the elegant way :) ]")
    while True:                                
        line = ser.readline().decode().strip()
        if line:
            line = line.split(',') # get list of 2 strings
            line = [Decimal(temp.strip()) for temp in line] # make line list of two Decimal objects
            t1, t2 = line # unpack line into two variables t1 and t2
            temp1.append(t1)                      
            temp2.append(t2)
            drawnow(make_fig)
            plt.pause(.000001)
            with open(out_fiile, 'a') as f:
                wrtr = csv.writer(f)
                wrtr.writerow(line)

            # as alternative to last 3 lines
            with open(out_fiile, 'a') as f:
                f.write(f'{t1},{t2}\n')
I didn't change your drawing of the plot and definitely program structure could be better
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
save in CSV and plotting in real time - by linkxxx - Aug-29-2019, 05:04 PM
RE: save in CSV and plotting in real time - by buran - Aug-30-2019, 11:11 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  how to save to multiple locations during save cubangt 1 604 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  Plotting by Time, error mansoorahs 1 773 May-16-2023, 09:46 AM
Last Post: Larz60+
  Non-blocking real-time plotting slow_rider 5 3,821 Jan-07-2023, 09:47 PM
Last Post: woooee
  Real time database satyanarayana 3 1,732 Feb-16-2022, 01:37 PM
Last Post: buran
  Real time data satyanarayana 3 28,090 Feb-16-2022, 07:46 AM
Last Post: satyanarayana
  Real time Detection and Display Gilush 0 1,819 Feb-05-2022, 08:28 PM
Last Post: Gilush
  time setup for realtime plotting of serial datas at high sampling rate alice93 6 3,858 Jan-07-2022, 05:41 PM
Last Post: deanhystad
  Real-Time output of server script on a client script. throwaway34 2 2,110 Oct-03-2021, 09:37 AM
Last Post: ibreeden
  Real Time Audio Processing with Python Sound-Device not working Slartybartfast 2 4,063 Mar-14-2021, 07:20 PM
Last Post: Slartybartfast
  Plotting A Time Series With Shaded Recession Bars adamszymanski 1 3,208 Jan-24-2021, 09:08 PM
Last Post: nealc

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020