MQTT interrupts

Hello,

I am trying to make a simple program using mqtt that start a stepper forward and reverse.

When I set at an mqtt topic “forward” the stepper moves forward, and when I set “reverse” stepper move at the opposite direction.

const int one_step = 200; 
const int number_of_circles = 10;

void stepper_forward() {
myStepper.setSpeed(60);
for( stepCount=0;stepCount< number_of_circles ;stepCount++){
myStepper.step(one_step);
yield();
}
}

void stepper_reverse() {
myStepper.setSpeed(60);
for( stepCount=0;stepCount< number_of_circles ;stepCount++){
myStepper.step(-one_step);
yield();
}
}

Everything works great, BUT I want to add one more function.

void stepper_stop()

My problem is that while each function (forward reverse) is executed my microcontroller doesn’t listen at the mqtt topic
so it doesn’t run stepper_stop().

Any thoughts ?

Thank you.

The problem is that your for loops block the execution of any other code for long periods of time. If you want your program to be responsive, you need to rework it so that there is no blocking code. You want the loop() function to be constantly running over and over again. The way to do this is to implement what’s called a state machine. You will have a global variable that stores the current program state. These states include:

  • Stepper forward
  • Stepper reverse
  • Stepper stop

Every time loop() runs, it will:

  • Check for incoming commands on the MQTT topic. If a command was received, set the state variable accordingly.
  • Take the appropriate action based on the value of the state variable. If the state indicates a move of the stepper, you will only call myStepper.step() once. You will have a global variable that stores the stepper count so you know how many steps were taken.

Thank you very much for your reply, I will try it the way you describe.