Saving serial data as it appears on the serial monitor

Viewed 65

This is my first post in here. I've signed up because I need help with the following:

I'm recording data from a sensor on Arduino UNO and I need to save the data with Python, for further processing in another Python script. I got my Arduino code working Ok, because when I look at the data in the serial monitor and serial plotter, it works fine.

However when I try to save the data on Python, the main problem is that it works very slowly.

My main goal is to save at least 1600 data samples per second on Python, because my Arduino sensor captures a signal that needs a frequency rate of at least 1.6 kHz. Since I want to have a 3 seconds register of the signal, I would need to record 4800 samples.

I've set a code with a loop to run 4800 times to capture the 4800 samples, with a "sleep" of 625 us between samples to space the samples in time. (1/1600 = 625 us) That way, I expected to save a a sample value every 625 us. The thing is, when I run my code, it takes A LOT more than 3 seconds to complete all 4800 samples, and therefore, my signal wasn't being recorded properly. I thought that it was because, in a previous code, I decoded the input string (something like, b'566/r/n), into a float in each iteration. I thought the decoding process time was comparable to my 625 us "waiting time" and that's why the sampling was taking too long.

However, even though I'm decoding the input data from the serial port in a later stage, and I've set a high baud rate of 115200, it still takes about 50 seconds to save the 4800 samples, when it should be doing that in 3 seconds.

Here's my code:

import serial
import time
import numpy as np

buffer = []

# set up the serial line
ser = serial.Serial('COM3', 115200)
time.sleep(2)


print("La recolección de datos comenzó")

# Read and record the data
print("Grabando señal")
for i in range(4800):                                #voy a tomar 4800 muestras = 1.6 kHz x 3 seg
        reading = ser.readline()         # read a byte string
        buffer.append(reading)
        time.sleep(0.000625)            # para una frecuencia de muestreo de 1.6 kHz

ser.close()

print("La recolección de datos terminó")

So basically, all I want to do is save the data from the serial port. I've read that I shouldn't use a timer on Python because the Arduino board ALREADY sends the data every 625 us (like I want), and so on Python I should just read and save the data on the serial port as it appears. I would need some help with that.

0 Answers
Related