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:
- the method
steer
is called with a motor, a direction and an amount of steps steer
formats the arguments to command for the arduino- this command is then sent to the arduino
- The arduino executes the command
- and then prints “done” to the Serial to let the pi know that he is finished
- 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?
diepzee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.