Arduino - Rotary Encoder - Servo Motor
In this tutorial, We are going to learn how to program Arduino to rotate a servo motor according to the rotary encoder's output value.
Or you can buy the following kits:
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand,
DIYables .
Buy Note: When using multiple servo motors, we recommend the PCA9685 16 Channel PWM Servo Driver Module to save MCU pins and make wiring easier.
If you do not know about servo motor and rotary encoder (pinout, how it works, how to program ...), learn about them in the following tutorials:

This image is created using Fritzing. Click to enlarge image
#include <Servo.h>
#define CLK_PIN 2
#define DT_PIN 3
#define SW_PIN 4
#define SERVO_PIN 9
#define DIRECTION_CW 0
#define DIRECTION_CCW 1
int counter = 0;
int direction = DIRECTION_CW;
int CLK_state;
int prev_CLK_state;
Servo servo;
void setup() {
Serial.begin(9600);
pinMode(CLK_PIN, INPUT);
pinMode(DT_PIN, INPUT);
prev_CLK_state = digitalRead(CLK_PIN);
servo.attach(SERVO_PIN);
servo.write(0);
}
void loop() {
CLK_state = digitalRead(CLK_PIN);
if (CLK_state != prev_CLK_state && CLK_state == HIGH) {
if (digitalRead(DT_PIN) == HIGH) {
counter--;
direction = DIRECTION_CCW;
} else {
counter++;
direction = DIRECTION_CW;
}
Serial.print("DIRECTION: ");
if (direction == DIRECTION_CW)
Serial.print("Clockwise");
else
Serial.print("Counter-clockwise");
Serial.print(" | COUNTER: ");
Serial.println(counter);
if (counter < 0)
counter = 0;
else if (counter > 180)
counter = 180;
servo.write(counter);
}
prev_CLK_state = CLK_state;
}
Connect Arduino to PC via USB cable
Open Arduino IDE, select the right board and port
Copy the above code and open with Arduino IDE
Click Upload button on Arduino IDE to upload code to Arduino
Open Serial Monitor
Rotate the rotary encoder
See the servo motor's rotation
See the result on Serial Monitor
DIRECTION: Clockwise | COUNTER/ANGLE: 19
DIRECTION: Clockwise | COUNTER/ANGLE: 26
DIRECTION: Clockwise | COUNTER/ANGLE: 34
DIRECTION: Clockwise | COUNTER/ANGLE: 46
DIRECTION: Clockwise | COUNTER/ANGLE: 53
DIRECTION: Counter-clockwise | COUNTER/ANGLE: 46
DIRECTION: Counter-clockwise | COUNTER/ANGLE: 34
DIRECTION: Counter-clockwise | COUNTER/ANGLE: 26
DIRECTION: Counter-clockwise | COUNTER/ANGLE: 16
DIRECTION: Counter-clockwise | COUNTER/ANGLE: 06
Read the line-by-line explanation in comment lines of source code!
We are considering to make the video tutorials. If you think the video tutorials are essential, please subscribe to our YouTube channel to give us motivation for making the videos.
※ OUR MESSAGES
You can share the link of this tutorial anywhere. Howerver, please do not copy the content to share on other websites. We took a lot of time and effort to create the content of this tutorial, please respect our work!