Python Forum
Real-time plot from serial port
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Real-time plot from serial port
#1
Hi,
I'm trying to plot the values from my uC's ADC in real-time. For this I'm using pyserial and Matlibplot. But I try to plot in real-time, I only get 1 value and it doesnt update in the while loop. When I save all the values and then plot them (no real-time plot), it works fine. Any suggestions? I'm trying to simulate an oscilloscope, so the faster the plot, the better. I also tried with 9600 baudrate. The second part of my code deals with the analysis of the data.
import time
import matplotlib.pyplot as plt
import serial
import numpy as np



######### Convierte data recibida a int
def bytes_to_int(bytes):
    result = 0
    for b in bytes:
        result = result * 256 + int(b)
    return result


##### Inicializar puerto serial
ser = serial.Serial(port='COM11', baudrate=38400)
#################

val_vol = []
val_time = []
count = 0
n = 40000  # Numero de muestras

######### Real-Time PLot
while (count <= n):
    # ser = serial.Serial(port='COM11', baudrate=38400, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, timeout=0.5)
    vol = ser.read()
    vol1 = bytes_to_int(vol)
    val_vol.append(vol1)
    val_time.append(time.clock())
    print(vol1)
    count += 1
    plt.plot(val_vol)  # Plot data

    plt.show(block=False)  # Plot in real time
    plt.pause(0.002)
    time.sleep(0.002)

#####################################


print(val_vol)


def find_nearest(array, value):  # Finds the nearest value to the max and min % set by user
    array = np.asarray(array)  # Make sure its an array
    idx = (np.abs(array - value)).argmin()  # Calculate the position of the value
    return array[idx]  # Returns value


##### Valores Criticos ##############
amplitud = max(val_vol) - min(val_vol)
valor = (amplitud * 0.9) + min(val_vol)
valor_min = (amplitud * 0.1) + min(val_vol)
################################

###### Inicializar arrays ############
res_list = []
res_list_min = []
time_index = []
time_index_min = []
####################################

##### Valores del 90 y 10% ################
index_valor = find_nearest(val_vol, valor)
index_valor_min = find_nearest(val_vol, valor_min)
####################################

##### For loop para encontrar index de valores #####
for i in range(0, len(val_vol)):
    if val_vol[i] == index_valor:
        res_list.append(i)
    if val_vol[i] == index_valor_min:
        res_list_min.append(i)
############################################

print("index valor", index_valor)
print("Res_list", res_list)
print("tamanio", len(val_time))

###### For loop para porcentaje mayor ########
for i in range(0, len(res_list)):
    time_index1 = val_time[res_list[i]]
    time_index.append(time_index1)
###############################################


###### For loop para porcentaje menor ########
for i in range(0, len(res_list_min)):
    time_index1_min = val_time[res_list_min[i]]
    time_index_min.append(time_index1_min)
###############################################


###### Crear lineas del 90 y 10 % #############
temp_1 = np.ones(len(val_time))  # Temp var for line
lin_max = valor * temp_1
lin_min = valor_min * temp_1
################################################


###### Tiempo critico #############
ts = abs(time_index[0] - time_index_min[0])
tb = abs(time_index[2] - time_index_min[2])
##############################################

##### Plot points ############
x_1 = np.array(time_index[0])
y_1 = index_valor
x_2 = np.array(time_index_min[0])
y_2 = index_valor_min
#########################################

print("time index", time_index)
print("El tiempo de subida es: ", ts, "El tiempo de bajada es: ", tb)
print(x_1, y_1)

####### Plotear data #####################
plt.plot(val_time, val_vol)
plt.plot(val_time, lin_max)
plt.plot(val_time, lin_min)
plt.plot(x_1, y_1, 'ro')
plt.plot(x_2, y_2, 'ro')
plt.show()
###########################################
Reply
#2
without digging into your code, I'd guess that this is some sort of delta issue where two readings in a row are equal
i thought perhaps you could study some of the following code to see how they handle:

package 1:
https://pypi.org/project/oscilloscope/
github: https://github.com/scientifichackers/oscilloscope

package 2:
https://pypi.org/project/pydatascope/
https://sourceforge.net/projects/pydatascope/

more: https://pypi.org/search/?q=oscilloscope
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Human Activity recognition in real time pihidream 0 1,473 Sep-20-2021, 09:55 AM
Last Post: pihidream
  How can draw a real-time marker on map using folium/leaflet Jupyter notebook C3PO 0 2,389 Dec-22-2020, 07:04 PM
Last Post: C3PO
  HeatMap plot with arduino serial data tshivam 0 3,176 Oct-08-2018, 10:57 AM
Last Post: tshivam

Forum Jump:

User Panel Messages

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