6 years, 1 month ago.

Stepper Motor Issue

Hello, I am experimenting with 2 steppers to make them run together using Threads. I am using STM32 Nucleo F767ZI development board. One of the stepper motors vibrates too much while running the code. But, they run smoothly while making them run separately. I think the issue is with the threads. What could be the better solution?

#include "mbed.h"
#include "stepperMotor.h"

Serial pc(USBTX, USBRX);

int recepticlestepspeed = 400 ;                                //motor speed for recepticle conveyor stepper
int recepticlenumstep = 800; 

int microtrackstep_speed = 400 ;                             //motor speed for microtrack conveyor stepper
int microtracknumstep = 133;

Thread *t1;                         
Thread *t2;                         
Thread *t3;                         
Thread *t4;                         

sMotor recepticle_conveyor(PF_5, PF_10, PA_7, PF_2);       

sMotor microtrack_conveyor(PA_3, PC_0, PC_3, PF_3);       


DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);

void func_stepper1()
{
        for(int i = 0; i<6; i++)
        {
            microtrack_conveyor.step(microtracknumstep,  0 , microtrackstep_speed);
        } 
}           
    
void func_stepper2()
{
     recepticle_conveyor.step(recepticlenumstep, 1 , recepticlestepspeed);   
}

void func_stepper2_return()
{
     recepticle_conveyor.step(recepticlenumstep, 0 , recepticlestepspeed);
}

void func_stepper1_return()
{
        for(int i=0; i<6; i++)
        microtrack_conveyor.step(microtracknumstep , 1 , microtrackstep_speed); 
}

int main() 
{
    int t; 
    while(1)
    {
        pc.printf("\n\r Press 1 to start: ");
        pc.scanf("%d", &t);
        if(t == 1)
        {   
            if(t1) delete t1; 
            if(t2) delete t2;
            t1 = new Thread;
            t2 = new Thread;
            t1->start(func_stepper1);
            t2->start(func_stepper1);
            wait(5);
            if(t3) delete t3; 
            if(t4) delete t4;
            t3 = new Thread;
            t4 = new Thread;
            t3->start(func_stepper1_return);
            t4->start(func_stepper2_return);
        }
    }
}            

1 Answer

6 years, 1 month ago.

If the system is switching between two tasks then things aren't going to always move smoothly. If you want them to move together in a smooth way then the best bet is to control both motors from one thread so that you can better control the relative timings of them. If you want them to be even closer in sync then create a library that controls two motors so that you can ensure they both step at exactly the same time.

Also you have an initialization error, t1-t4 should default to being null or you risk calling delete on an invalid pointer the first time around. You are also not checking that the threads have finished before deleting them.

How would you create that library where both the motors can run in sync?

posted by Rishabh Gupta 30 Mar 2018