我准备了短测试代码来通过串口控制步进电机(使用AccelStepper库)。该代码使用三个命令M - 将电机移动到定义的位置,H - 用于中止操作,P - 用于检查当前电机步进的位置。每个表彰都必须以“#”结束。因此,当我写M500#意味着电机将开始移动直到达到500. 我的问题/问题是如何中止此操作??? 串口被阻塞,直到RunToPosiotion功能完成。
#include <AccelStepper.h>
#include <MultiStepper.h>
AccelStepper stepper = AccelStepper(AccelStepper::HALF4WIRE, 4, 5, 6, 7);
String MyString;
String Command;
int Value;
void setup() {
Serial.begin(57600);
stepper.setMaxSpeed(400);
stepper.setAcceleration(600);
stepper.setCurrentPosition(100);
}
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
if (inChar == '#') {
SerialCommand(MyString);
MyString = "";
}
else {
MyString += inChar;
}
}
}
void loop() {
}
void SerialCommand(String ASCOM_Command) {
Command = String(ASCOM_Command.charAt(0));
String Txt_Value = ASCOM_Command.substring(1);
Value = Txt_Value.toInt();
/*Commands, an example: M500# - start motor to move until get 500 position
P - check actual focuser position
M - Move to specific position called by client application
H - Halt / Abort
*/
switch (ASCOM_Command.charAt(0)) {
case 'P':
Serial.println(stepper.currentPosition());
break;
case 'M':
stepper.moveTo(Value);
stepper.runToPosition();
break;
case 'H':
stepper.stop();
Serial.println("H#");
break;
}
}
答案 0 :(得分:0)
阅读accelstepper文档并按照runtoPosition的提示进行操作:
Dont use this in event loops, since it blocks.
请改为run()
:
快速保持循环(),每次只调用run()。