// By NMDWeerasinghe @COTMD
// run the stepper motor, given no steps, with given speed and given direction
#define stepPin 2
#define directionPin 3
#define halfStepInterval 20 //inversly related to speed
#define directionInPin 10
#define startPin 9
#define busytPin 4
int halfStepdelay;
int noOfSteps;
int speed;
int prvSpeed;
int prvNoOfSteps;
bool start;
bool clockwise;
bool prvDirection;
bool msgPrint = false;
//bool busy;
void Rotate(int steps, bool Clockwise);
void setup() {
pinMode(stepPin, OUTPUT);
pinMode(directionPin, OUTPUT);
pinMode(directionInPin, INPUT);
pinMode(startPin, INPUT);
halfStepdelay = halfStepInterval;
//busy = false;
Serial.begin(9600);
/*
Serial.println("Test run started !");
digitalWrite(busytPin,HIGH);
delay(500);
Rotate(100, 1);
digitalWrite(busytPin,HIGH);
delay(1500);
Rotate(100, 0);
Serial.println("Test run finished !");
*/
prvNoOfSteps = -1; //analogRead(A0) ;
prvSpeed = -1;//analogRead(A0);
prvDirection = -1;//digitalRead(directionInPin);
}
void loop() {
noOfSteps = analogRead(A0) ;
speed = analogRead(A1);
halfStepdelay = map(speed,0,1023,150,4) ;
clockwise = digitalRead(directionInPin);
start = digitalRead(startPin);
if(prvNoOfSteps != noOfSteps)
{
prvNoOfSteps = noOfSteps;
/*
Serial.print("No of steps to rotate : ");
Serial.println(noOfSteps);
delay(350);
*/
msgPrint = false;
}
if(prvSpeed != speed)
{
prvSpeed = speed;
/*
Serial.print("Speed : ");
Serial.println(map(speed,0,1023,0,100));
delay(350);
*/
msgPrint = false;
}
if(prvDirection != clockwise)
{
prvDirection = clockwise;
/*
Serial.print("Direction : ");
if(clockwise) Serial.println("clockwise");
else Serial.println("anticlockwise");
delay(350);
*/
msgPrint = false;
}
if(start)
{
Rotate(noOfSteps, clockwise);
msgPrint = false;
}
else if(not msgPrint)
{
Serial.println("Adjust No of Steps, Speed, direction and Press Start button to begin");
Serial.print("No of steps to rotate : ");
Serial.print(noOfSteps);
Serial.print(" , ");
Serial.print("Speed : ");
Serial.print(map(speed,0,1023,0,100));
Serial.print(" , ");
Serial.print("Direction : ");
if(clockwise) Serial.println("clockwise");
else Serial.println("anticlockwise");
Serial.println();
Serial.println();
delay(350);
msgPrint = true;
}
}
void Rotate(int noOfSteps, bool Clockwise)
{
digitalWrite(directionPin,Clockwise);
digitalWrite(busytPin,HIGH);
for(int i=0; i<noOfSteps ; i++)
{
digitalWrite(stepPin,HIGH);
delay(halfStepdelay);
digitalWrite(stepPin,LOW);
delay(halfStepdelay);
}
digitalWrite(busytPin,LOW);
}