I have a python script that sends motor speed values to an arduino with the pyserial library, however the data comes in fast and needs to be proccessed by the arduino and sent to an l298n motor controller. Everything works fine until about 10 seconds in where the blinking orange light (the one that flashes every time serial data is sent) goes solid instead of flashing, and my python script is having to wait a really long time to go past sending the serial message. After some research i suspected the serial buffer may be filling, and having to wait to proccess each command before accepting the next serial input, so whenever the arduino receives a serial message, at the end of the code i end serial a start it again as i saw a post saying that should flush the buffer, however this has not worked and the arduino is still freezing.
The code flashed to the arduino:
String serialRead;
String motorL;
String motorR;
String directionL;
String directionR;
int motorLS = 7;
int motorL1 = 6;
int motorL2 = 5;
int motorR1 = 4;
int motorR2 = 3;
int motorRS = 2;
void setup() {
Serial.begin(1000000);
pinMode(motorL1, OUTPUT);
pinMode(motorL2, OUTPUT);
pinMode(motorR1, OUTPUT);
pinMode(motorR2, OUTPUT);
pinMode(motorLS, OUTPUT);
pinMode(motorRS, OUTPUT);
}
void loop() {
if (Serial.available()>0) {
serialRead = Serial.readStringUntil('.');
motorL = serialRead.charAt(0);
motorL += serialRead.charAt(1);
motorL += serialRead.charAt(2);
motorR = serialRead.charAt(3);
motorR += serialRead.charAt(4);
motorR += serialRead.charAt(5);
directionL = serialRead.charAt(6);
directionR = serialRead.charAt(7);
Serial.println(motorL);
Serial.println(motorR);
Serial.println("Char 6: " + directionL);
Serial.println("Char 7: " + directionR);
analogWrite(motorLS, motorL.toInt());
analogWrite(motorRS, motorR.toInt());
if (directionL=="1") {
Serial.println("1");
digitalWrite(motorL1, LOW);
digitalWrite(motorL2, HIGH);
digitalWrite(motorR2, LOW);
digitalWrite(motorR1, HIGH);
}
else {
Serial.println("0");
digitalWrite(motorL1, HIGH);
digitalWrite(motorL2, LOW);
digitalWrite(motorR2, HIGH);
digitalWrite(motorR1, LOW);
}
Serial.end();
Serial.begin(1000000);
}
}
Demo python script:
import serial
import random
arduino = serial.Serial(port='COM3', baudrate=1000000, timeout=.001)
while True:
# rjust takes any 1 or 2 digit number and puts leading 0s infront to make it 3 digits
data = str(random.randint(0, 255)).rjust(3, '0') + str(random.randint(0, 255)).rjust(3, '0') + "11."
arduino.write(bytes(data, 'utf-8'))
i dont need to use all the data, whenever the arduino finishes it should use the latest data coming in and update, without slowing down the python script as it also needs to proccess data in realtime and any pauses might miss some things. If anyone knows how to overcome this issue your help will be much appreciated!