我有一个Arduino草图,控制两个不同的电机,一个步进电机和一个直流电机,使用Adafruit电机屏蔽库。草图的主要功能是接受串行输入上的字符串参数,格式为:(intmotorId, intmotorDirection, intmotorSpeed, intdegrees, intholdingTorque)并将其解析为控制电机行为的各种参数。
对于直流电动机,我希望它在关闭之前运行一定的时间间隔,这将转化为特定的移动度。我正在使用millis()功能来检查何时应在不阻塞进一步串行输入的情况下关闭电机。我的问题是,我不知道如何执行命令关闭电机只一次,if语句检查时间增量是否大于runinterval反复调用函数RAMOTOR-> fullloff ()每runinterval。
我试过在if (currentMillis - preousmillis>runinterval)使此操作只发生一次,但是,该方法的问题是,如果变量为false那么preousmillis永远不会被设置为currentMillis。
这是我的主循环的全部:
unsigned long currentMillis = millis();
if (Serial.available() > 0) {
//Read char array input from serial monitor
String input = Serial.readStringUntil('n');
/*Pass the string to the class member "ParseInput" of the parsemotorparameters object, which will
retrieve the motor behavior parameters such as speed and steps to move and return a true boolean which sets the motor run state variable*/
parsemotorparameters.ParseInput(input);
//Set the runtime in seconds for the RA motor
runinterval = parsemotorparameters.ReturnMotorRuntime(DEG_PER_SEC);
/*If motor ID returned from "ParseInput" is 1, then run the RA motor for calculated period of time that translates to
degrees moved*/
if (parsemotorparameters.ReturnMotorId() == 1) {
Serial.println(runinterval);
//RAMOTOR->setSpeed(RASpeed);
//RAMOTOR->run(parsemotorparameters.ReturnMotorDirection());
CheckRAStatus = true;
}
else {
//If the holding torque boolean variable is true, then apply power to the stepper motor continously even if the motor is not activley stepping
if (parsemotorparameters.ReturnHoldingTorque()) {
//Set the stepper motor speed
//DECMOTOR->setSpeed(parsemotorparameters.ReturnMotorSpeed());
/*Adafruit stepper motor class member accepts the following parameters
step(uint8_t #steps, uint8_t direction 1 or 0, uint8_t step mode) */
//DECMOTOR->step(parsemotorparameters.ReturnMotorSteps(), parsemotorparameters.ReturnMotorDirection(), MICROSTEP);
}
//If the holding torque boolean variable is false, then remove power from the stepper motor as soon as it's done moving
else {
//DECMOTOR->setSpeed(parsemotorparameters.ReturnMotorSpeed());
//DECMOTOR->step(parsemotorparameters.ReturnMotorSteps(), parsemotorparameters.ReturnMotorDirection(), MICROSTEP);
//DECMOTOR->release();
}
}
debug();
}
if (currentMillis - previousMillis > runinterval) {
previousMillis = currentMillis;
//RAMOTOR->fullOff();
Serial.println("OFF");
CheckRAStatus = false;
}
不知道是什么问题。你需要一些布尔标志
bool raMotorOn = false;
然后在RAMOTOR->run()
call周围设置为true并修改if
if (raMotorOn && (currentMillis - previousMillis > runinterval)) {
raMotorOn = false;
...
}
不确定我是否正确理解了您的问题声明和代码,但是您可以使用CheckRAStatus
作为标志来防止重复调用fullOff()
。
if (CheckRAStatus && currentMillis - previousMillis > runinterval) {
previousMillis = currentMillis;
RAMOTOR->fullOff();
Serial.println("OFF");
CheckRAStatus = false;
}