I am trying to transmit MPU6050 accelerometer data + data from 3 potentiometers from Arduino to Raspberry Pi. I do post processing here (on Raspberry Pi) and then transfer the data back to Arduino to move actuators. However my problem is that when I try to write the processed data back to Arduino, I see that even the stream of incoming data from Arduino starts getting corrupted and everything becomes really slow . Even If I just read serial data from Arduino, things are slower if than if I do the processing on Arduino directly. Also, the accelerometer data seems to become unresponsive i.e. its value doesn't change if I move the accelerometer. Everything just works fine if all the processing is done on Arduino. I don't know what is going wrong. Below are my Arduino and Python functions / codes.
Arduino Code:
void send_rec_data(){
Serial.print(Kp);
Serial.print(",");
Serial.print(Kd);
Serial.print(",");
Serial.print(Ki);
Serial.print(",");
Serial.println(Theta_x);
delay(20);
if (Serial.available()>0){ // Read data sent by Raspberry Pi / Piserial
str_data = Serial.readString();
int firstCommaIndex = str_data.indexOf(',');
cmd = str_data.substring(0, firstCommaIndex); // This stores the Scaled output from the Raspberry Pi
param1 = str_data.substring(firstCommaIndex+1); // This stores the error from the Raspberry Pi to decide motor roattion direction
Output = cmd.toFloat(); my_error = param1.toFloat(); // Change the outputs from string to float
blink_led(); // Blink LEDS if data is received from Raspberry Pi
}
}
Python Code:
while 1:
data = cont.get_serial_data(arduino)
time.sleep(0.02)
if data is not None:
Kp, Kd, Ki, Theta_x = data
print(" \n Arduino sent Kp = ", Kp , "Kd = ",Kd , "Ki = ", Ki, "Theta_x = ", Theta_x)
cont.set_tunings(Kp, Kd, 0)
Output_scaled = cont.Compute_PID_Output(Input = Theta_x) # Compute the output of PID Algorithm
ff = str(Output_scaled)+','+str(cont.error)
arduino.write(ff.encode())
print("\n Computed data sent TO ARDUINO Output_scaled = ", Output_scaled, "Error = ", cont.error)
arduino.close()
I have spent quiet sometime to resolve the issue byputting delays, flushing buffer but nothing has worked so far. Can someone please help.
Thanks.