Как удалить задержку из моего кода при построении графика входящих данных в реальном времени?Python

Программы на Python
Ответить
Anonymous
 Как удалить задержку из моего кода при построении графика входящих данных в реальном времени?

Сообщение Anonymous »

У меня есть код, который работает отлично. Он отображает и фильтрует данные, и данные тоже верны. Единственная проблема заключается в том, что между тензодатчиком и отображением данных существует задержка около 3 секунд. Я хочу убрать эту задержку или, по крайней мере, сделать ее как можно меньшей.
Тензометр подключен к HX711, который подключен к Arduino Nano Every, который подключен к мой ноутбук.
Я не уверен, но предполагаю, что задержка вызвана функцией def read_weight().
Вот код что у меня есть:

Код: Выделить всё

import matplotlib.pyplot as plt
from collections import deque
from scipy.signal import filtfilt
import time
import serial

# --- Arduino Serial Connection --
# Set up serial connection to Arduino
arduino_port = "COM3"
baud_rate = 9600
ser = serial.Serial(arduino_port, baud_rate)
time.sleep(1)

def read_weight():
# Read a line of serial data from Arduino and decode it
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8').strip()
try:
weight = float(line)
return weight
except ValueError:
print("Error: Could not convert data to float.")
return None
return None

# Prints the values of the weight. Good for testing
# while True:
#     test = read_weight()
#     if test is not None:
#         print(test)

# Smooth the initial data parameters
n = 5  # Smoothing factor
b = [1.0 / n] * n  # Coefficients for the filter
a = 1  # Denominator coefficients (for a moving average filter)

# Plot setup
plt.ion()  # Turn on interactive mode
fig, ax = plt.subplots(figsize=(10, 6))
line_original, = ax.plot([], [], color="b", label="Original Data")
line_smooth, = ax.plot([], [], color="r", label="Smoothened Data")
plt.xlabel("Time (s)")
plt.ylabel("Weight (g)")
plt.title("Real-Time Load Cell Data Plot")
plt.legend()
plt.grid(True)
plt.tight_layout()

# Initialize empty lists for the real-time plot
display_x = deque(maxlen=100)           # Stores the last 100 data points for time
display_y = deque(maxlen=100)           # Stores the last 100 data points for weight
display_y_smooth = deque(maxlen=100)    # Stores the last 100 data points for smoothed y-axis

# Start time for the plot
start_time = time.time()

# --- Live Plotting Loop ---
while True:
# Read weight from the Arduino
weight = read_weight()

if weight is not None:
current_time = time.time() - start_time  # Get the time since the start
display_x.append(current_time)  # Append the current time
display_y.append(weight)  # Append the new weight reading
# Smoothen using current points (if we have enough points)

if len(display_y) >= n:  # Only apply smoothing once enough points are collected
# Dynamically define padlen to be smaller than the number of data points
padlen = min(len(display_y) - 1, 3 * n)
display_y_smooth = filtfilt(b, a, list(display_y), padlen=padlen)

# Update data on plot
line_original.set_data(display_x, display_y)
if len(display_y_smooth) > 0:
line_smooth.set_data(display_x, display_y_smooth)

# Update plot limits
ax.set_xlim(max(0, current_time - 10), current_time + 1)
ax.set_ylim(min(display_y) - 50, max(display_y) + 50)

# Redraw the plot
plt.pause(0.01)  # Pause briefly to simulate data arrival
time.sleep(0.01)

ser.close()
plt.ioff()  # Turn off interactive mode once complete
plt.show()
Я пробовал удалить или уменьшить значения plt.pause и time.sleep, но безрезультатно. Я также попытался добавить интервал к фильтру, чтобы он фильтровал более крупные интервалы. Это работало, но только если код работал в течение короткого времени. Чем дольше выполнялся код, тем больше становилась задержка. И я попытался увеличить скорость передачи данных до 115200, но Python (или мой ноутбук) не справился с этим, и тогда он вообще не отображался.

Подробнее здесь: https://stackoverflow.com/questions/791 ... e-incoming
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»