# Driving stepper motor

Status
Not open for further replies.

#### Veketti

##### Full Member level 3
Hi,

I made a small program to drive stepper motor with PIC 16F1847, TB6600 driver and 17HS2408 motor. Motor is driven 36° in every button push which equals 160 microsteps. I had no problem just driving the motor forward but when I needed it to "shake" bit by changing direction it wasn't accurate 36 degrees anymore in every step. Like every tenth step it jumped more and all the others too little. Also my calculations didn't match. To my understanding this code should drive first 31 steps forward, then 6 steps backward, 26 steps forward and start it over again. Do this until 176 steps are done. Maybe my bitwise operations are not correct or I've miswritten the conditions? Thank you for help.

Code:
#define DELAY 800
#define STEPS 176 // 160 steps forward is 36 degrees. x=10240/(64-y) (y = stepsbackwards)
#define STEPSBACKWARDS 6 // from 32 steps this many steps backwards
bit pulse;
unsigned int i;

void DriveMotor(void) {
int u = 0;
for(i=0 ; i < STEPS ; i++){
if ((i & (1<<5)) && (u < STEPSBACKWARDS)) { // after every 32th step, will have 6 steps backwards
LATB.b1 = 0; // direction backwards
u++;
} else LATB.b1 = 1; // direction forward
if (!(i & (1<<5))) { // next 32 steps normally forward
u = 0;
LATB.b1 = 1;
}

pulse = !pulse;
LATB.B2 = pulse;
delay_us(DELAY);

}
delay_ms(400);
}

void main() {
InitMain();

while(1) {
if (button(&PORTB,3,1,0))
{
LATB.b1 = 1;
DriveMotor() ;
}
}

}

Last edited: