ledstick/python/plotserial_power.py
Patrick Moessler fc4005cc49 v2
2025-02-24 00:29:15 +01:00

77 lines
1.7 KiB
Python

# /// script
# requires-python = ">=3.13"
# dependencies = [
# "matplotlib",
# "numpy",
# "pyserial",
# ]
# ///
import time
from struct import unpack
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
from serial import Serial
SYNC = bytes.fromhex("001180007fff1100")
BLOCK_LENGTH = 8
last_time = time.time()
def main() -> None:
ser = Serial("COM5", baudrate=1000000)
x1 = np.arange(BLOCK_LENGTH)
y1 = np.zeros(BLOCK_LENGTH)
x2 = np.arange(BLOCK_LENGTH)
y2 = np.zeros(BLOCK_LENGTH)
fig, ax = plt.subplots()
graph1 = ax.plot(x1, y1)[0]
graph2 = ax.plot(x2, y2)[0]
plt.ylim(0, 2 ** 32)
def sync():
synced = False
syncbuf = bytearray(ser.read(len(SYNC)))
while not synced:
if syncbuf[: len(SYNC)] == SYNC:
synced = True
break
syncbuf.append(ser.read(1)[0])
syncbuf.pop(0)
if not synced:
raise ConnectionError
print(syncbuf.hex())
print("waiting for sync...")
sync()
print("synced")
def update(frame):
global last_time
sync()
block = ser.read(4 * 2 * BLOCK_LENGTH)
x = unpack(f"{BLOCK_LENGTH}I{BLOCK_LENGTH}I", block)
now = time.time()
print(block.hex())
print(x)
print(f"elapsed: {now-last_time}")
last_time = now
avg, current = x[:BLOCK_LENGTH], x[BLOCK_LENGTH:]
y1[:] = avg[:]
y2[:] = current[:]
graph1.set_ydata(y1)
graph2.set_ydata(y2)
anim = FuncAnimation(
fig, update, frames=None, cache_frame_data=False, interval=256 / 24000
)
plt.show()
if __name__ == "__main__":
main()