Why Is the RaspberryPi-Arduino Serial communication only working sometimes?

I have connected a Raspberry Pi with an Arduino to steer stepper motors.
This is the arduino code:

#include <AFMotor.h>

AF_Stepper motor_x(200, 1);
AF_Stepper motor_z(200, 2);


String msg;

void setup() {
  // put your setup code here to run once:
  Serial.begin(9600);
  motor_x.setSpeed(65);
  motor_z.setSpeed(50);
}

// [x|z][f|b][steps]
// xf400

void loop() {
  readSerialPort();
  if (msg.length() >= 3) {
    auto motor = msg[0] == 'x' ? motor_x : motor_z;
    auto direction = msg[1] == 'f' ? FORWARD : BACKWARD;
    msg.remove(0, 2);
    int steps = msg.toInt();
    motor.step(steps, direction, SINGLE);
    delay(500);
  }
  Serial.println("done");
}

void readSerialPort() {
  msg = "";
  if (Serial.available()) {
    delay(10);
    while (Serial.available() > 0) {
      msg += (char)Serial.read();
    }
    Serial.flush();
  }
}

And this is the raspberry code:

from time import sleep
from enum import Enum
import serial

class Direction(Enum):
    FORWARD = "f"
    BACKWARD = "b"


class Motor(Enum):
    MOVE_X = "x"
    MOVE_Y = "y"
    MOVE_Z = "z"
    PUMP = "p"
    SEED = "s"


class Arduino:

    def __init__(self, port: str):
        self.port = port

    def get_serial(self) -> serial.Serial:
        ser = serial.Serial(self.port, 9600, timeout=120)
        ser.flush()
        return ser

    def send_command(self, cmd: str) -> bool:
        try:
            with self.get_serial() as arduino:
                sleep(0.1)
                if arduino.is_open:
                    print(f"Connected to arduino {self.port}")
                    arduino.write(cmd.encode())
                    while arduino.in_waiting == 0: pass
                    if arduino.in_waiting > 0:
                        answer = arduino.readline()
                        print(f"Got an answer from arduino: {answer}")
                        arduino.flushInput()
            return True
        except:
            return False

    def steer(self, motor: Motor, direction: Direction, length: int) -> bool:
        return self.send_command(f"{motor.value}{direction.value}{length}")
    
uno = Arduino("/dev/ttyACM0")

r = uno.steer(Motor.MOVE_X, Direction.BACKWARD, 2880)

print(r)

This is how the code should work:

  1. the method steer is called with a motor, a direction and an amount of steps
  2. steer formats the arguments to command for the arduino
  3. this command is then sent to the arduino
  4. The arduino executes the command
  5. and then prints “done” to the Serial to let the pi know that he is finished
  6. Which is than read by the pi so he knows he can continue with the rest of the code.

Steps one to two work perfectly fine. Also, there is no problem establishing a connection from the pi to the arduino.
But often, the message received by the arduino is empty or just contains a few characters. Just as the response that is sent back to the pi.

The code starts to work sometimes after a few commands exchanged and a few uploads to the pi.
But even when it is working (which is seldom), the response often is just “nern” or just “n”.
I think that this also happens to the command sent to the arduino so all that he finds is just some random letters.
Probably, the error lies in the usage of the flush method.
How can I make my code working reliably?

New contributor

diepzee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật