Rotary Encoders - 0928
Rotary Encoders - 0928
Introduction
Rotary encoders are electronic devices that can measure mechanical rotation. They can be used in two
fashions – As a control or as a device to measure the rotation of a shaft.
When used as a control, rotary encoders can be much more versatile than a potentiometer. They can be
used when you need a very precision control, and they are not subject to drift due to temperature.
As a device to measure mechanical rotation rotary encoders have several uses. One of them is to
measure the rotation of a DC gearmotor.
Today we will look at both types of rotary encoders. I will show you how to hook them up to an
Arduino and I’ll give you some demonstration sketches that you can run yourself.
So let’s get started!
Rotary Encoders
A rotary encoder, which can also be referred to as a shaft encoder, is an electro-mechanical device that
can convert the angular position (rotation) of a shaft to either an analog or digital output signals. We
will be focusing on digital devices today.
There are two main types of rotary encoder: absolute and incremental. The difference is the absolute
encoder gives the precise position of the shaft in degrees, whereas the incremental encoder reports how
many increments the shaft has moved, but not its actual position.
Rotary encoders are used in many different applications including industrial controls, robotics,
optomechanical mice and trackballs, CNC machines and printers.
Rotary Encoder Operation
There are several different types of rotary encoders. I’m restricting this discussion to the simpler
“incremental” encoders. These are sometimes called quadrature or relative rotary encoders.
These encoders have two sensors and output two sets of pulses. The sensors, which can be magnetic
(hall effect) or light (LED or Laser), produce pulses when the encoder shaft is rotated.
As there are two sensors in two different positions they will both produce the same pulses, however,
they will be out of phase as one sensor will pulse before the other one. Which sensor goes first is
determined by the direction of rotation.
In the above example the encoder shaft is spinning clockwise. The sensor on the top is triggered before
the bottom one, so the top set of pulses precedes the bottom set.
If the encoder shaft is rotated counterclockwise then the bottom set of pulses will be delivered before the
top set.
In both cases the pulses can be counted to determine how much the shaft has rotated. By checking to see
which pulse comes first we can determine the direction of rotation.
Control Encoder
The control encoder we are going to use is a very common device, and it’s available from several
sources. It’s also included in the infamous “37 in one” sensor kit that is available at many electronic
stores and online.
The encoder can be mounted exactly like a potentiometer, and it has a D-shaft to accept a knob. It also
has its own push button momentary contact switch that can be activated by pressing down upon the
shaft.
The pinouts of the control encoder are as follows:
GND – The Ground connection.
+V – The VCC or positive supply voltage, usually 3.3 or 5-volts.
SW – The pushbutton switch output. When the shaft is depressed this goes to ground level.
DT – The Output A connection.
CLK – The output B connection.
I will show you how to use this control encoder in a moment, but first, let’s look at the other rotary
encoder we will be discussing today.
Motor Encoder
Motor encoders are mounted on the shaft of a DC motor and can count the amount that the motor shaft
has moved. Coupled with a motor driver, this will allow you to create a feedback mechanism that can
permit you to specify how much you would like the shaft to turn.
You can also use these encoders as a tachometer to measure the speed that the shaft is rotating.
The encoder I’m illustrating here is the one that is attached to the gear motor I am using in my DB1
Robot from my Build a REAL Robot series of articles and videos. It is a goBILDA 5201 Series Spur
Gear Motor with a built-in encoder.
Other motor encoders should have similar connections.
The connections are very basic:
VCC – the 5-volt power supply input.
GND – The Ground connection.
CH A – Output A.
CH B – Output B.
We will see how to use this with an Arduino to measure the motor RPM very soon.
Reading Control Encoders
We will begin our rotary encoder experiments using the control encoder.
Reading a control encoder with an Arduino is actually fairly straightforward. We just need to read input
pulses and count them. We also need to determine which set of pulses is occurring first, so that we can
determine the direction of rotation.
Arduino Control Encoder Test Hookup
Here is how we will hook up our first rotary encoder experiment.
You will notice that in addition to the rotary encoder I have added a couple of LEDs. These will indicate
the direction that we are spinning the encoder shaft.
The dropping resistors for the two LEDs are any value from 150 to 470 ohms, in the illustration I show
220 ohm resistors.
Incidentally, none of the pins used on the Arduino are critical. You can change them around, provided
that you alter the sketch accordingly.
Arduino Control Encoder Test Sketch
Now that you have your encoder and LEDs hooked up you’ll need a sketch to make it all work. Here is
the one I came up with:
Rotary Encoder Demo
1 /*
3 rot-encode-demo.ino
7 https://dronebotworkshop.com
8 */
12 #define inputDT 5
13
14 // LED Outputs
15 #define ledCW 8
16 #define ledCCW 9
17
18 int counter = 0;
19 int currentStateCLK;
20 int previousStateCLK;
21
23
24 void setup() {
25
27 pinMode (inputCLK,INPUT);
28 pinMode (inputDT,INPUT);
29
31 pinMode (ledCW,OUTPUT);
32 pinMode (ledCCW,OUTPUT);
33
35 Serial.begin (9600);
36
39 previousStateCLK = digitalRead(inputCLK);
40
41 }
42
43 void loop() {
44
47
48 // If the previous and the current state of the inputCLK are different then a pulse has occured
49 if (currentStateCLK != previousStateCLK){
50
53 if (digitalRead(inputDT) != currentStateCLK) {
54 counter --;
55 encdir ="CCW";
56 digitalWrite(ledCW, LOW);
57 digitalWrite(ledCCW, HIGH);
58
59 } else {
61 counter ++;
62 encdir ="CW";
63 digitalWrite(ledCW, HIGH);
64 digitalWrite(ledCCW, LOW);
65
66 }
67 Serial.print("Direction: ");
68 Serial.print(encdir);
70 Serial.println(counter);
71 }
73 previousStateCLK = currentStateCLK;
74 }
We start the sketch by defining some constants to represent the inputs from the encoder and the outputs
to the two LEDs.
Next, a few integer variables are defined. The counter variable represents the count that will be modified
by turning the controller, it can be a positive or negative number..
The currentStateCLK and previousStateCLK variables hold the state of the CLK output (Output B),
these are used as part of the system to determine the direction of rotation.
A string called encdir is defined, it will be used when we print the current direction of rotation to the
serial monitor.
Now on the the Setup section.
The Setup is pretty straightforward, we setup the serial monitor, define the connections to the encoder as
inputs and the connections to the two LEDs as outputs.
At the end of the Setup we read the current value of the CLK pin and assign it to
the previousStateCLK variable.
And now the Loop, where all the action takes place!
We check the CLK input and compare it to the previousStateCLK value. If it has changed then a pulse
has occurred.
Next the logic to determine the direction of rotation. We now look at the DT pin on the encoder module
and compare it to the current state of the CLK pin.
If it is different then we are rotating counterclockwise. We then decrement the counter variable value,
set encdir to hold a value of “CCW” and turn on the red (CCW) LED.
If, on the other hand, the two values are the same then we are moving clockwise. We do the opposite –
increment the counter, write “CW” to the encdir variable and turn on the Green (CW) LED.
After we print our results to the serial monitor we update previousStateCLKwith the current state of
CLK.
Then we do it all over again.
Load the sketch and observe both the serial monitor and the two LEDs. When the CW LED is lit the
value in the serial monitor should increment. Otherwise, the CCW LED will be lit and the value will
decrement.
You may use this sketch as the basis for your own encoder projects. In fact, the next demo does exactly
that!
Control Encoder with Servo Motor
The next experiment we will perform is to use a rotary encoder to control the position of a servo motor.
This is a great application for a rotary encoder as it will let you position the servo motor very precisely.
It would be a great way to operate a robot arm, for example, as it would let you precisely position the
arm and its grip. Of course, you would need to add more encoders and more servo motors to the design.
Arduino Servo Hookup
The hookup for the servo motor controller is illustrated below:
One thing to note is that I have used a separate power supply for the servo motor. I always recommend
doing this as the servo can induce electrical noise onto the 5-volt line that the Arduino uses. But, if you
really must, you can eliminate the extra supply and use the Arduino 5-volt output.
Again the pinouts are not critical but if you do change them you’ll need to make sure to use a digital I/O
pin on the Arduino that supports PWM for the servo control lead.
Arduino Servo Control Sketch
Here is the sketch you will need to use to control the servo motor with the rotary encoder.
Servo with Encoder
1 /*
3 rot-encode-servo-demo.ino
8 https://dronebotworkshop.com
9 */
10
12 #include <Servo.h>
13
15 #define inputCLK 4
16 #define inputDT 5
17
20
21 int counter = 0;
22 int currentStateCLK;
23 int previousStateCLK;
24
25 void setup() {
26
28 pinMode (inputCLK,INPUT);
29 pinMode (inputDT,INPUT);
30
32 Serial.begin (9600);
33
35 myservo.attach(9);
36
39 previousStateCLK = digitalRead(inputCLK);
40
41 }
42
43 void loop()
44
46 currentStateCLK = digitalRead(inputCLK);
47
48 // If the previous and the current state of the inputCLK are different then a pulse has occured
49 if (currentStateCLK != previousStateCLK){
50
53 if (digitalRead(inputDT) != currentStateCLK) {
54 counter --;
55 if (counter<0){
56 counter=0;
57 }
58
59 } else {
61 counter ++;
62 if (counter>180){
63 counter=180;
64 }
65
66 }
67
69 myservo.write(counter);
70
71 Serial.print("Position: ");
72 Serial.println(counter);
73 }
75 previousStateCLK = currentStateCLK;
76 }
If you compare this sketch to the previous one you’ll undoubtedly notice many similarities. It starts out
by defining many of the same variables, without the LEDs of course as they are not used here.
We also include the built-in Arduino Servo library and define a myservo object to represent our servo
motor.
The counter, currentStateCLK and previousStateCLK variables are used again.
In the Setup we attach the myservo object to pin 9, which is where the control lead of the servo motor is
connected.
The Loop is also very much like the previous sketch, with some notable exceptions.
Since a servo motor only accepts a value between 0 and 180 we limit our results to this range.
After getting the counter value we use it to position the servo motor. The value should represent the
position of the servo arm in degrees.
We print this position to the serial monitor, reset the previousStateCLKvariable and do it all over again.
When you run the sketch observe both the arm on the servo motor and your serial monitor. The arm
position should correspond to the reading on the serial monitor.
This is a very accurate method of positioning a servo motor.
Using Gearmotor Encoders
Now that we have seen how to use control encoders let’s turn our attention to encoders used with
gearmotors.
As with the control encoders, the motor encoders have two outputs. This will allow you to determine the
direction that the motor is spinning.
I am actually NOT going to decode the motor direction as I don’t really see the point – after all I am the
one spinning the motor in a specific direction so I already know which way it is going!
Motor Encoder Output
Before I hook up the encoder to an Arduino thought it might be a good opportunity to take a look at the
pulses that it produces. So I hooked the two outputs up to my oscilloscope.
As you can see from the scope traces the two outputs are nice square waves, offset from each other.
You could also use the two square waves to make a more accurate encoder, reading the combination of
pulses to get much finer resolution. However, as my encoder gives out 374 pulses per rotation it is
already accurate to less than a degree. That is accurate enough for my purposes.
Arduino Motor Encoder Hookup
Now let’s test the encoder with an Arduino. We will hook it up, along with a motor driver and a
potentiometer to control speed and read the RPM of the motor.
The motor driver I am using is the Cytron MD10C, which I have used in the article Controlling Large
DC Gearmotors. You can read more details about it there if you like. It is very simple to use, requiring
only a power supply for the motor to power its internal logic circuits.
I also used a 12-volt power supply, as that is the recommended voltage for my motor.
The potentiometer I used was a 10k linear-taper. Any value from 5k or higher will work.
The connections from the Arduino to the encoder are as follows:
Arduino Pin Encoder Pin
Ground GND
3 CH A (Output A)
Actually, you could have used Output B instead, as I’m not measuring the direction of rotation, just the
position.
The input connections to the Cytron MD10C motor driver are as follows:
Arduino Pin Cytron MD10C Input Pin
12 DIR (Direction)
10 PWM
Ground GND
I’m not actually using the DIR pin as in this sketch I’m not controlling the motor direction, so you can
leave it out if you wish.
The output of the motor controller is connected to, what else, the motor! And the power supply is
connected to the power inputs, be sure to observe the proper polarity.
The potentiometer is hooked to analog input A0, so we can control the motor speed.
Arduino Motor Encoder Sketch
Now that we have our motor hooked up it’s time to run the sketch to control and read its speed.
Motor Encoder RPM
1 /*
3 motor-encoder-rpm.ino
9 https://dronebotworkshop.com
10 */
11
14
16 #define ENC_IN 3
17
19 #define PWM 10
21 #define DIR 12
22
24 int speedcontrol = 0;
25
28
31
34 long currentMillis = 0;
35
37 int rpm = 0;
38
40 int motorPwm = 0;
41
42 void setup()
43 {
45 Serial.begin(9600);
46
48 pinMode(ENC_IN, INPUT_PULLUP);
49
51 pinMode(PWM, OUTPUT);
52 pinMode(DIR, OUTPUT);
53
54 // Attach interrupt
56
58 previousMillis = millis();
59 }
60
61 void loop()
62 {
63
66
69
71 currentMillis = millis();
73 previousMillis = currentMillis;
74
75
76 // Calculate RPM
78
82 Serial.print(motorPwm);
83 Serial.print('\t');
85 Serial.print(encoderValue);
86 Serial.print('\t');
88 Serial.print(rpm);
89 Serial.println(" RPM");
90 }
91
92 encoderValue = 0;
93 }
94 }
95
96 void updateEncoder()
97 {
99 encoderValue++;
100 }
In this sketch we will need to use interrupts to count pulses from our encoder, this is because our pulses
will be arriving pretty quickly as compared to reading an encoder control.
Before we can use the sketch we need to know how many pulses our encoder will produce for one
rotation of the motor. You can determine this from the specification sheet for your motor. Without this
value, you won’t be able to get an accurate RPM reading.
My motor produces 374 pulses per rotation, so I set the constant ENC_COUNT_REV to this value.
The next few lines define the pins that connect to the motor encoder, motor driver and to the
potentiometer.
We will use the long encoderValue to keep track of the pulses we receive from the encoder. Then we
will count how many of these occur in one second. By multiplying this by 60 we’ll know how many
pulses we should get in a minute. If we divide this value by the ENC_COUNT_REV then we can
determine the RPM of the motor shaft.
We will measure the one-second interval by keeping track of the number of milliseconds that have
elapsed. The Arduino millis() function counts the number of milliseconds since the Arduino was last
reset or powered on, so we can get out interval using this.
At the bottom of the sketch is an interrupt handler, it simply increments the value of encoderValue when
it is triggered by a pulse from the encoder.
In the Setup we attach the interrupt handler to the pin connected to the encoder (pin 3), we trigger on a
rising pulse.
The Loop starts with reading the value of the analog input connected to the potentiometer. We use
the Arduino Map Function to change its range to 0-255 and an analogWrite command to send a PWM
signal with this value to the motor controller. This results in the motor turning at the desired speed.
We see if 1000 milliseconds have elapsed, if so we read the count and do the math to determine the
RPM. We then print the values to the serial monitor. Note the use of the tab character to format these
results in nice columns.
After printing the value we reset the encoderValue variable to zero so we can begin counting again.
Load the sketch and power everything up. Turn the potentiometer and observe the motor turning, as well
as the value on the serial monitor.
Conclusion
Rotary encoders are pretty versatile, they can be used as both controls and as sensors.
As controls, they have much greater precision than a potentiometer, and they cost just a little bit more. I
know that I’m planning to create many of my future designs using them.
I also will be building a complete motor controller using the rotary encoder included with my gear
motor. Being able to position my robot to within less than a millimeter is an extremely attractive
proposition.
I hope this article, and its associated video, have opened your eyes to some tasks you can perform with a
rotary encoder.
** v0928