Imagine that you want to control your stepper motor through a bluetooth and you give an order to make 14000 steps. A beginer would write the code as following:
for (int i = 0; i < 14000; i++) {
motor.step(1);
}
But what if you want to stop this process in the middle because something went wrong? Or if you want to run 2 motors at the same time? The for cycle blocks the code and this code will not react to your new orders until the for cycle for 1 motor finishes.
The solution is easy - do not use a for cycles, if you want to manage more processes at the "same" time. Loop() is already a cycle, so we are going to use it with "if". Here is my general structure of a code when you can manage as many processes as you want and not to block each other:
First we declare some variables:
bool moveMotor1 = false;
bool moveMotor2 = false;
int motor1StepsNum, motor2StepsNum;
Our loop will be easy:
void loop() {
ReceiveBTData();
if (moveMotor1) MoveMotor1();
if (moveMotor2) MoveMotor2();
}
We create a functions for moving motors with "if":
void MoveMotor1() {
if (motor1StepsNum > 0) {
motor1.step(1);
motor1StepsNum--;
}
else moveMotor1 = false;
}
void MoveMotor2() {
if (motor2StepsNum > 0) {
motor2.step(1);
motor2StepsNum--;
}
else moveMotor2 = false;
}
And finally we handle a bluetooth communication where we initialize or stop processes:
#define moveMotor1Value 81
#define moveMotor2Value 82
#define stopMotor1Value 91
#define stopMotor2Value 92
#define cancelValue 99
void ReceiveBTData() {
if (Serial.available() > 0) {
byte receivedValue = Serial.read();
if (receivedValue == moveMotor1Value) {
motor1StepsNum = Serial.read() + (Serial.read() << 8);
moveMotor1 = true;
}
if (receivedValue == moveMotor2Value) {
motor2StepsNum = Serial.read() + (Serial.read() << 8);
moveMotor2 = true;
}
if (receivedValue == stopMotor1Value) {
moveMotor1 = false;
}
if (receivedValue == stopMotor2Value) {
moveMotor2 = false;
}
if (receivedValue == cancelValue) {
moveMotor1 = false;
moveMotor2 = false;
}
}
}
Comments