C code

The code is written with the WINAVR C- compiler. The speed can be controlled with the speed parameter.

// program name: stepper
// date: 13 feb 2017
// author: www.avrprojects.net
// target device : ATMEGA328 stepper motor
// Drives a unipolar stepper motor.
// The sequence of control signals for 4 control wires is as follows:
// Step C0 C1 C2 C3
// 1 1 0 1 0
// 2 0 1 1 0
// 3 0 1 0 1
// 4 1 0 0 1
//
// stepper(speed,steps) speed: motor speed; steps: Moves the motor x steps. If the number is negative, the motor moves in the reverse direction.


#include <avr/io.h>
#include <util/delay.h>

void left(int step_speed)
{
PORTB = 0b00001001;
_delay_ms(step_speed);
PORTB = 0b00001010;
_delay_ms(step_speed);
PORTB = 0b00000110;
_delay_ms(step_speed);
PORTB = 0b00000101;
_delay_ms(step_speed);
}

void right(int step_speed)
{
PORTB = 0b00000101;
_delay_ms(step_speed);
PORTB = 0b00000110;
_delay_ms(step_speed);
PORTB = 0b00001010;
_delay_ms(step_speed);
PORTB = 0b00001001;
_delay_ms(step_speed);
}

void stepper(int speed, int steps)
{
int x;

if (steps > 0)
for (x = 1; x < steps ; x++)
{
left(speed);
}
else if (steps < 0)
for (x = 1; x < abs(steps) ; x++)
{
right(speed);
}
}

int main (void)
{
DDRB = 0x0f;// set lower 4 bits portB as output
DDRD = 0x00;// set portD as input

int speed = 10;
char input;

while(1)
{
input = PIND;
if (input == 0x01)
{
stepper(speed, 2);
}

else if (input == 0x02)
{
stepper(speed, -2);
}
}
}