https://dronebotworkshop.com/rotary-encoders-arduino/
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
rot-encode-demo.ino
Demonstrates operation of Rotary Encoder
Displays results on Serial Monitor
DroneBot Workshop 2019
https://dronebotworkshop.com
*/
// Rotary Encoder Inputs
#define inputCLK 4
#define inputDT 5
// LED Outputs
#define ledCW 8
#define ledCCW 9
int counter = 0;
int currentStateCLK;
int previousStateCLK;
String encdir ="";
void setup() {
// Set encoder pins as inputs
pinMode (inputCLK,INPUT);
pinMode (inputDT,INPUT);
// Set LED pins as outputs
pinMode (ledCW,OUTPUT);
pinMode (ledCCW,OUTPUT);
// Setup Serial Monitor
Serial.begin (9600);
// Read the initial state of inputCLK
// Assign to previousStateCLK variable
previousStateCLK = digitalRead(inputCLK);
}
void loop() {
// Read the current state of inputCLK
currentStateCLK = digitalRead(inputCLK);
// If the previous and the current state of the inputCLK are different then a pulse has occured
if (currentStateCLK != previousStateCLK){
// If the inputDT state is different than the inputCLK state then
// the encoder is rotating counterclockwise
if (digitalRead(inputDT) != currentStateCLK) {
counter --;
encdir ="CCW";
digitalWrite(ledCW, LOW);
digitalWrite(ledCCW, HIGH);
} else {
// Encoder is rotating clockwise
counter ++;
encdir ="CW";
digitalWrite(ledCW, HIGH);
digitalWrite(ledCCW, LOW);
}
Serial.print("Direction: ");
Serial.print(encdir);
Serial.print(" -- Value: ");
Serial.println(counter);
}
// Update previousStateCLK with the current state
previousStateCLK = currentStateCLK;
}
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 previousStateCLK with 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.
/*
Rotary Encoder with Servo Motor Demo
rot-encode-servo-demo.ino
Demonstrates operation of Rotary Encoder
Positions Servo Motor
Displays results on Serial Monitor
DroneBot Workshop 2019
https://dronebotworkshop.com
*/
// Include the Servo Library
#include <Servo.h>
// Rotary Encoder Inputs
#define inputCLK 4
#define inputDT 5
// Create a Servo object
Servo myservo;
int counter = 0;
int currentStateCLK;
int previousStateCLK;
void setup() {
// Set encoder pins as inputs
pinMode (inputCLK,INPUT);
pinMode (inputDT,INPUT);
// Setup Serial Monitor
Serial.begin (9600);
// Attach servo on pin 9 to the servo object
myservo.attach(9);
// Read the initial state of inputCLK
// Assign to previousStateCLK variable
previousStateCLK = digitalRead(inputCLK);
}
void loop()
// Read the current state of inputCLK
currentStateCLK = digitalRead(inputCLK);
// If the previous and the current state of the inputCLK are different then a pulse has occured
if (currentStateCLK != previousStateCLK){
// If the inputDT state is different than the inputCLK state then
// the encoder is rotating counterclockwise
if (digitalRead(inputDT) != currentStateCLK) {
counter --;
if (counter<0){
counter=0;
}
} else {
// Encoder is rotating clockwise
counter ++;
if (counter>180){
counter=180;
}
}
// Move the servo
myservo.write(counter);
Serial.print("Position: ");
Serial.println(counter);
}
// Update previousStateCLK with the current state
previousStateCLK = currentStateCLK;
}
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 previousStateCLK variable 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 |
5V (5-volt output) | VCC |
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.
/*
Gearmotor Rotary Encoder Test
motor-encoder-rpm.ino
Read pulses from motor encoder to calculate speed
Control speed with potentiometer
Displays results on Serial Monitor
Use Cytron MD10C PWM motor controller
DroneBot Workshop 2019
https://dronebotworkshop.com
*/
// Motor encoder output pulse per rotation (change as required)
#define ENC_COUNT_REV 374
// Encoder output to Arduino Interrupt pin
#define ENC_IN 3
// MD10C PWM connected to pin 10
#define PWM 10
// MD10C DIR connected to pin 12
#define DIR 12
// Analog pin for potentiometer
int speedcontrol = 0;
// Pulse count from encoder
volatile long encoderValue = 0;
// One-second interval for measurements
int interval = 1000;
// Counters for milliseconds during interval
long previousMillis = 0;
long currentMillis = 0;
// Variable for RPM measuerment
int rpm = 0;
// Variable for PWM motor speed output
int motorPwm = 0;
void setup()
{
// Setup Serial Monitor
Serial.begin(9600);
// Set encoder as input with internal pullup
pinMode(ENC_IN, INPUT_PULLUP);
// Set PWM and DIR connections as outputs
pinMode(PWM, OUTPUT);
pinMode(DIR, OUTPUT);
// Attach interrupt
attachInterrupt(digitalPinToInterrupt(ENC_IN), updateEncoder, RISING);
// Setup initial values for timer
previousMillis = millis();
}
void loop()
{
// Control motor with potentiometer
motorPwm = map(analogRead(speedcontrol), 0, 1023, 0, 255);
// Write PWM to controller
analogWrite(PWM, motorPwm);
// Update RPM value every second
currentMillis = millis();
if (currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
// Calculate RPM
rpm = (float)(encoderValue * 60 / ENC_COUNT_REV);
// Only update display when there is a reading
if (motorPwm > 0 || rpm > 0) {
Serial.print("PWM VALUE: ");
Serial.print(motorPwm);
Serial.print('\t');
Serial.print(" PULSES: ");
Serial.print(encoderValue);
Serial.print('\t');
Serial.print(" SPEED: ");
Serial.print(rpm);
Serial.println(" RPM");
}
encoderValue = 0;
}
}
void updateEncoder()
{
// Increment value for each pulse from encoder
encoderValue++;
}
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.
Resources
Sketches – ZIP file with all of the sketches used in this article.
'사물인터넷' 카테고리의 다른 글
SD Card Experiments with Arduino (0) | 2021.07.04 |
---|---|
Using a Real Time Clock with Arduino (0) | 2021.07.04 |
Build a Digital Level with MPU-6050 and Arduino (0) | 2021.07.04 |
Using BIG Stepper Motors with Arduino (0) | 2021.07.04 |
Stepper Motor with Hall Effect Limit & Homing Switches (0) | 2021.07.04 |