I have a very basic Arduino setup :

  • Arduino Uno
  • Rotary encoder
  • Nema 17 stepper motor + A4988 driver

How can I control the rotation of the motor with the rotary encoder? How can I get it to make one full rotation (200 steps) if I make a full rotation of the encoder (20 pulses)?

UPDATE : I managed to get the driver + motor setup going using this diagram and the code on this page : https://howtomechatronics.com/tutorials/arduino/how-to-control-stepper-motor-with-a4988-driver-and-arduino/


Now all i need is to properly wire the rotary encoder and add the code for syncing the motor with the encoder.

Can someone help me out with a diagram and a piece of code ?

  • so you can control the motor with commands from Serial Monitor. you can print to Serial Monitor the position of the rotary encoder. but you can't put it together? – Juraj Oct 11 '18 at 11:51
  • Juraj, i am a complete noob when it comes to arduino, i have followed tutorials but none of them have exactly what i need... – Jordan Oct 11 '18 at 11:56
  • can you control the motor with commands from Serial Monitor? – Juraj Oct 11 '18 at 12:07

I will give you a direction.


Take the code form here for rotary encoder. encoder0Pos will display which way rotary encoder is moving.


Here is the code for stepper.

I will draft up a small code now, change the pin numbering yourself

int val;
int encoder0PinA = 3;
int encoder0PinB = 4;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int scaledEncoder=0;
int encoder0LastVal=0;
int n = LOW;
const int stepsPerRevolution = 200; 
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0; 
void setup() {
  pinMode (encoder0PinA, INPUT);
  pinMode (encoder0PinB, INPUT);
void loop() {

int x = readEncoder();


int readEncoder()
 n = digitalRead(encoder0PinA);
  if ((encoder0PinALast == LOW) && (n == HIGH)) {
    if (digitalRead(encoder0PinB) == LOW) {
    } else {
    Serial.print (encoder0Pos);
    Serial.print ("/");
  encoder0PinALast = n;
     { return 1;}

 else {return 3;}


void driveStepper( int encoder)
{ if(encoder==1)


  else {}

I really suck at formatting code, but this is something similar. I cannot test it, I wrote it just like that. You can make it nicer by implementing switch case statement.

Basic idea is that you check which way encoder turned, pass it to driver function, and based on that drive your motor 10 steps forward or backward (since you wanted a linear 1:10 relation)

Hope this helps

| improve this answer | |
  • In the encoder read it compares if it is bigger or smaller, but the editor does not show that, idk why. if(encoder0LastPos<encoder0pos) {return 0;} should be there – Atizs Oct 11 '18 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.