1 year, 11 months ago.

How to pause and resume threads, and how to switch between them?

Hello everyone, I have been recently introduced to Mbed due to it's multithreading capabilities.

I am attempting to create a state machine which controls 3 stepper motors. Sometimes they will all move at the same time, and sometimes they may move individually, depending on which state the application is at.

For example:

1st state: Move 1 Description: Move the first stepper motor, and change the flags to trigger the next state

2nd state: Move 2 n 3 Description: Move only the second and third stepper motors, wait till all motion is completed before proceeding to next state

3rd state: Move 1 Description: Move only the first stepper motor.

Now, the way I have tried to tackle this is to define 3 threads for each stepper motor. Ie

<<Thread Stepper1(osPriorityHigh); Thread Stepper2(osPriorityHigh2); Thread Stepper3(osPriorityHigh3);

Then for each stepper I have defined their required functions/movements, and made completion flags, ie:

<< bool Stepper1flag = false; bool Stepper2flag = false; bool Stepper3flag = false;

void Move1_Home(){ move, and when complete, flag to true Stepper1flag = true; }

int main(){ stepper1.start(Move1); stepper2.start(Move2); stepper3.start(Move3);

while(1){}

}

I am expecting that once the flags for the 'move' function are up, the next functions that will execute would be the ones stated in state 2. However, what's happening is that only the Move1 executes, and the rest of the code does not execute.

I would appreciate if anyone can shed some insight and/or comment on what I'm doing wrong here.

1 Answer

1 year, 11 months ago.

Using multiple threads adds a lot of extra complication and points of failure. The general rule is you should not add extra threads unless you really need them. Threads end up being useful when you find yourself doing a lot of waiting. In otherwords doing so much waiting that it interferes with timing in other parts of your program. This happens a lot with offboard communication where you send out some data and then have to wait for a reply. So you break the communication off into a separate thread and now it can wait while your main thread works on other things.

For your application, since these stepper motors are operating in sequence one after the other, it seems like a single thread and plain old state machine should work fine. How long do your Move1, Move2, Move 3 operations actually take to run? Does your application have to do anything else while these are running? Or can you just sit there and wait for Move 1 operation to run to completion?