Skip to content

Instantly share code, notes, and snippets.

@gsvster
Last active September 17, 2021 16:35
Show Gist options
  • Save gsvster/8cee94b5d0ad21deb8f11f613646c92e to your computer and use it in GitHub Desktop.
Save gsvster/8cee94b5d0ad21deb8f11f613646c92e to your computer and use it in GitHub Desktop.
Control a Stepper Motor using Arduino and Rotary Encoder
#include <Stepper.h>
/*-----( Declare Constants, Pin Numbers )-----*/
int in1 = 2;
int in2 = 3;
int in3 = 4;
int in4 = 5;
// init rotary encoder
int pinA = 7;
int pinB = 8;
int encoderPosCount = 0;
int pinALast;
int aVal;
int bVal;
boolean bCW;
//---( Number of steps per revolution of INTERNAL motor in 4-step mode )---
#define STEPS_PER_MOTOR_REVOLUTION 32
//---( Steps per OUTPUT SHAFT of gear reduction )---
#define STEPS_PER_OUTPUT_REVOLUTION 32 * 64 //2048
/*-----( Declare objects )-----*/
// create an instance of the stepper class, specifying
// the number of steps of the motor and the pins it's
// attached to
//The pin connections need to be 4 pins connected
// to Motor Driver In1, In2, In3, In4 and then the pins entered
// here in the sequence 1-3-2-4 for proper sequencing
Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 2, 4, 3, 5);
/*-----( Declare Variables )-----*/
int Steps2Take;
void setup() /*----( SETUP: RUNS ONCE )----*/
{
// rotary encoder setup
pinMode(pinA, INPUT);
pinMode(pinB, INPUT);
pinALast = digitalRead(pinA);
Serial.begin(9600);
// Nothing (Stepper Library sets pins as outputs)
}/*--(end setup )---*/
void loop() /*----( LOOP: RUNS CONSTANTLY )----*/
{
aVal = digitalRead(pinA);
bVal = digitalRead(pinB);
if ((pinALast == HIGH) && (aVal == LOW)){
if (bVal == LOW){
Steps2Take = STEPS_PER_OUTPUT_REVOLUTION / 50; // Rotate CW 1/2 turn
small_stepper.setSpeed(500);
small_stepper.step(Steps2Take);
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
encoderPosCount--;
}
else {
Steps2Take = - STEPS_PER_OUTPUT_REVOLUTION / 50; // Rotate CW 1/2 turn
small_stepper.setSpeed(500);
small_stepper.step(Steps2Take);
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
encoderPosCount++;
}
Serial.print (encoderPosCount);
Serial.print ("/");
}
pinALast = aVal;
}/* --(end main loop )-- */
/* ( THE END ) */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment