我正在做一个项目,我使用串口从我的电脑向 arduino 发送字符串,arduino 读取它们并根据字符串移动一个或另一个电机,这是代码:
#include <AccelStepper.h>
#include <AFMotor.h>
AF_Stepper motor1(200, 1);
AF_Stepper motor2(200, 2);
String steps= "";
void forwardstep1() {
motor1.onestep(FORWARD, SINGLE);
}
void backwardstep1() {
motor1.onestep(BACKWARD, SINGLE);
}
void forwardstep2() {
motor2.onestep(FORWARD, SINGLE);
}
void backwardstep2() {
motor2.onestep(BACKWARD, SINGLE);
}
AccelStepper stepper1(forwardstep1, backwardstep1);
AccelStepper stepper2(forwardstep2, backwardstep2);
void setup() {
Serial.begin(9600);
Serial.println("Stepper program!");
stepper1.setMaxSpeed(200.0);
stepper2.setMaxSpeed(200.0);
stepper1.setAcceleration(100.0);
stepper2.setAcceleration(100.0);
}
void loop() {
}
void serialEvent() {
while(Serial.available()) {
int inChar = Serial.read();
Serial.print("Echo:");
Serial.write(inChar);
if (isDigit(inChar)) {
steps += (char)inChar;
}
if (inChar == 'u') {
Serial.print("Up:" + steps);
Serial.println();
long POSITION = stepper1.currentPosition() + steps.toInt();
stepper1.runToNewPosition(POSITION);
steps = "";
Serial.println();
}
if (inChar == 'U') {
Serial.print("Up:" + steps);
Serial.println();
long POSITION = stepper2.currentPosition() + steps.toInt();
stepper2.runToNewPosition(POSITION);
steps = "";
Serial.println();
}
}
}
我遇到的问题是当我移动 stepper1 然后尝试移动 stepper2 时它不再移动,除非我重置 arduino。
谢谢!