Is there incompatibility between sending matrices via USB and displaying them in heatmaps in Python?

20 Views Asked by At

I'm trying to display a heat map with 16x16 matrices sent via USB, I'm simulating a pressure sensor. I made code just to display the sent matrices in Python and had a great reception rate. Then I made a separate code that generates random matrices and displays them in a heatmap using matplotlib's animation library, which had a very good result in its display rate per second. When I tried to unify the two codes to plot the heat map according to the matrices sent, the display rate was very slow, with a display of 1 matrix per second while more or less 15 matrices are sent in the same interval, I wanted understand why there is this incompatibility in the display of data received via USB.

Code that receives the matrices sent via USB (Working well):

import serial
import json
import numpy as np

#Configurar a porta serial e a taxa de transmissão
ser = serial.Serial('COM3', 115200)

while True:
    # Ler uma linha da porta serial como bytes
    data_bytes = ser.readline()

    # Decodificar os dados recebidos como uma string UTF-8
    data_str = data_bytes.decode().strip()

    try:
        # Carregar os dados JSON
        data_json = json.loads(data_str)

        # Converter matrizes para arrays NumPy
        matriz = np.array(data_json['Valores_de_Tensao'])
        
        # Exibir as matrizes convertidas usando numpy
        print("\nMatriz Recebida:")
        print(matriz)

    except json.JSONDecodeError as e:
        print(f"Erro ao decodificar JSON: {e}")

Code that plots random matrices using animation (Working well):

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()
heatmap = ax.imshow(np.zeros((16, 16)), cmap='plasma')

heatmap.set_clim(vmin=0, vmax=1) 

def update(data):
    heatmap.set_array(data)
    return heatmap,

def data_gen():
    while True:
        matriz_aleatoria = np.random.rand(16, 16)
        yield matriz_aleatoria

ani = animation.FuncAnimation(fig, update, data_gen, interval=0, blit=True)
plt.show()

Code unifying the two cases (Working poorly):

import json
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import serial

# Configurar a porta serial e a taxa de transmissão
ser = serial.Serial('COM3', 115200)

# Configurar figura e eixos para o mapa de calor
fig, ax = plt.subplots()
heatmap = ax.imshow(np.zeros((16, 16)), cmap='plasma')

# Definir limites de cores do mapa de calor
heatmap.set_clim(vmin=0, vmax=1) 

def update(data):
    try:
        # Carregar os dados JSON
        data_json = json.loads(data)

        # Converter matrizes para arrays NumPy
        matriz = np.array(data_json['Valores_de_Tensao'])

        # Atualizar o mapa de calor com a nova matriz
        heatmap.set_array(matriz)
        return heatmap,

    except json.JSONDecodeError as e:
        print(f"Erro ao decodificar JSON: {e}")
        return heatmap,

def data_gen():
    while True:
        # Ler uma linha da porta serial como bytes
        data_bytes = ser.readline().strip()
        yield data_bytes

ani = animation.FuncAnimation(fig, update, data_gen, interval=0, blit=True)
plt.show()
0

There are 0 best solutions below