I am working on a project involving an Arduino microcontroller and a Python-based AI model. My goal is to use the Arduino to read sensor data and send it to a PC via serial communication (UART) for real-time analysis.
What I have tried: I have set up the Arduino code to read sensors and use Serial.println() to output the data. On the PC side, I am attempting to use the pyserial library in Python to read these incoming strings.
The issue: However, I am struggling with data synchronization. Sometimes the Arduino sends data faster than Python reads it, leading to a buffer overflow or incomplete strings.
Here is my current code:
import serial
# Replace 'COM3' with the actual serial port name you are using.
ser = serial.Serial('COM3', 9600)
while True:
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8').rstrip()
print(line)
void setup() {
Serial.begin(9600); // Set the serial transmission rate to 9600
}
void loop() {
int sensorValue = analogRead(A0); // Read sensor values
Serial.println(sensorValue); // Transmit values as strings
delay(100); // Delay 100 milliseconds
}
Goal: I want to ensure the data stream is stable enough for an AI model to perform predictive analysis. Could anyone suggest a robust way to handle serial data streaming from a microcontroller to a PC for machine learning applications?