-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSTM32PythonTest
More file actions
54 lines (40 loc) · 1.55 KB
/
Copy pathSTM32PythonTest
File metadata and controls
54 lines (40 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import serial
import time
import matplotlib.pyplot as plt
from collections import deque
# Configure the serial connection to the correct port and baud rate
# For stm32, baud rate is typically 115200
ser = serial.Serial('COM5', 115200, timeout=1)
time.sleep(0.1) # Wait for the connection to establish
# The deque is used to store the last 200 data points, but the 201st will remove the first
# This allows for the plot to show a moving window of data rather than just growing indefinitely
data = deque(maxlen=200)
# plt.ion allows for the plot to be updated dynamically
plt.ion()
# Sets up the figure for plotting
fig, ax = plt.subplots()
while True:
# Read a line from the serial port, decodes from binary to string, and strips newline and spaces
line = ser.readline().decode().strip()
if line:
print(line)
# Attemps to convert the character string to an integer for plotting
try:
value = float(line)
except ValueError as e:
print("What??", e)
continue
# Updates the data array with the new value
data.append(value)
# Clears the previous plot and redraws with the updated data
# It is plotting an array, so it will not be losing values, just shifting them
ax.clear()
ax.plot(data)
# Sets the y-axis limits to 0-4V and x-axis limits to 0-200 samples
ax.set_ylim(0, 4)
ax.set_xlim(0, 200)
ax.set_title('Voltage Readings from STM32')
ax.set_xlabel('Sample Number')
ax.set_ylabel('Voltage (V)')
# Pause briefly to allow the plot to update
plt.pause(0.001)