Ardunio driving EasyDriver vs and Sparkfun Stepper motor

I’d accidently posted this on the PIC code stream but as far as I can tell it probably belongs here.

I’ve set up a test rig for the EasyDriver v3 and Sparkfun stepper motor to learn what’s involved in driving them from an Ardunio (using interupts to get the variable frequency).

It’s based around a library example for the Timer1 library for the Ardunio.

It generates a random frequency between 1 and 9500 and random direction changes and ramps the speed between settings.

I’m using pin13 as the PWM pin which seems to work fine. I plan to eventually try using a second interupt timer as well to drive a second motor and then configure the pair to drive a telescope via largish worm gears.

/*

  • Based on the Timer1 library example at

  • http://www.arduino.cc/playground/Code/Timer1 by jesse dot tane at gmail dot com

  • Modified and extended to test the Sparkfun Easydriver V3 and Sparkfun stepper motor

  • September 2009

  • Tested with a heavy worm attached (but not meshed to the worm gear) with a goal of using it for a telescope drive.

  • Includes a facility to ramp the speed when altering speed or changing direction

*/

#include “TimerOne.h”

int dirPin = 12;

int stepperPin = 13;

int stepperState = LOW;

boolean Dir = true;

// Max frequency 9500 (low torque)

// Min frequency 1

int frequency = 1;

int convertFrequency(int pFrequency);

void step();

void ramp(int pFrequency, int pNewFrequency);

void setup()

{

pinMode(dirPin, OUTPUT);

digitalWrite(dirPin,true);

pinMode(stepperPin, OUTPUT);

randomSeed(analogRead(0));;

Timer1.initialize(convertFrequency(frequency)); // initialize timer1, and set the timer

Timer1.pwm(stepperPin, 50); // setup pwm on stepper pin

Timer1.attachInterrupt(step); // attaches step() as a timer overflow interrupt

}

void step()

{

stepperState = !stepperState;

digitalWrite(stepperPin, stepperState);

}

int convertFrequency(int pFrequency)

{

return 1000000/pFrequency;

}

void ramp(int pFrequency, int pNewFrequency)

{

int stepSize = 20;

int stepDelay = 30;

if ( pFrequency > pNewFrequency )

{

while ( pFrequency > pNewFrequency )

{

pFrequency = constrain(pFrequency - stepSize, pNewFrequency, pFrequency);

Timer1.setPeriod( convertFrequency(pFrequency));

delay(stepDelay) ;

}

}

else if ( pFrequency < pNewFrequency )

{

while ( pFrequency < pNewFrequency )

{

pFrequency = constrain(pFrequency + stepSize, pFrequency, pNewFrequency);;

Timer1.setPeriod( convertFrequency(pFrequency));

delay(30) ;

}

}

}

void loop()

{

int newFrequency = random(1,9500);

int changeDir = random(1,4);

if (changeDir = 1)

{

ramp(frequency, 0);

frequency = 0;

Dir = !Dir;

digitalWrite(dirPin,Dir);

delay(50);

}

ramp(frequency, newFrequency);

frequency = newFrequency;

delay(9000);

}