// Control Stepper Motor

#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

#define Speed_Control  A0  //10k Potentiometer
#define Reverse A1 // Counterclockwise Button
#define Stop A2 // Stop Button
#define Forward A3 // Clockwise Button
#define in1 11 // Motor  Pin A-
#define in2 10 // Motor  Pin A+
#define in3 9  // Motor  Pin B+ 
#define in4 8  // Motor  Pin B-

int read_ADC;
int Speed_LCD;
int Speed;
int Step;
int Mode=0;

void setup() { // Put your setup code here, to run once
  
pinMode(Speed_Control, INPUT); // Declare potentiometer as input 
pinMode(Reverse, INPUT_PULLUP); // Declare Reverse button as input
pinMode(Stop, INPUT_PULLUP); // Declare stop button as input
pinMode(Forward, INPUT_PULLUP); // Declare forward button as input
pinMode(in1, OUTPUT); // Declare as output for Pin A-
pinMode(in2, OUTPUT); // Declare as output for Pin A+
pinMode(in3, OUTPUT); // Declare as output for Pin B+  
pinMode(in4, OUTPUT); // Declare as output for Pin B-
  
lcd.begin(16,2);  
lcd.setCursor(5,0);
lcd.print("Control");
lcd.setCursor(2,1);
lcd.print("Stepper Motor");
delay(2000); // Waiting for a while
lcd.clear();
}

void loop() { 

read_ADC = analogRead(Speed_Control); // Read analogue to digital value 0 to 1023 
Speed = map(read_ADC, 0, 1023, 100, 0);
Speed_LCD = map(read_ADC, 0, 1023, 0, 100); 
lcd.setCursor(3,0);
lcd.print("Speed:");
lcd.print(Speed_LCD); 
lcd.print("%  ");

if(digitalRead (Reverse) == 0){Mode = 1;} // For Counterclockwise rotation
if(digitalRead (Stop) == 0){Mode = 0;} // For Stop
if(digitalRead (Forward) == 0){Mode = 2;} // For Clockwise rotation

// Display status on LCD
lcd.setCursor(0,1);
if(Mode==0){ lcd.print("     Stop       ");} 
if(Mode==1){ lcd.print("    Reverse     ");}
if(Mode==2){ lcd.print("    Forward     ");}

if(Speed_LCD>0){
if(Mode==1){  
Step = Step+1;
if(Step>3){Step=0;}    
call_Step(Step); // Stepper motor rotates CCW (Counterclockwise)
}

if(Mode==2){
Step = Step-1;
if(Step<0){Step=3;}  
call_Step(Step); // Stepper motor rotates CW (Clockwise)
}

delay(Speed); }  

}

// 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

void call_Step(int i){
    switch (i) {
      case 0: // 1010
        digitalWrite(in1, HIGH);
        digitalWrite(in2, LOW);
        digitalWrite(in3, HIGH);
        digitalWrite(in4, LOW);
      break;
      case 1: // 0110
        digitalWrite(in1, LOW);
        digitalWrite(in2, HIGH);
        digitalWrite(in3, HIGH);
        digitalWrite(in4, LOW);
      break;
      case 2: // 0101
        digitalWrite(in1, LOW);
        digitalWrite(in2, HIGH);
        digitalWrite(in3, LOW);
        digitalWrite(in4, HIGH);
      break;
      case 3: // 1001
        digitalWrite(in1, HIGH);
        digitalWrite(in2, LOW);
        digitalWrite(in3, LOW);
        digitalWrite(in4, HIGH);
      break;
    }
  }