Arduino Projects

Encoder with Arduino: Rotary Encoder, Absolute Encoder, Incremental Optical Encoder Encoder with Arduino

What is an Encoder?

An encoder is an electromechanical feedback device that is used in many industries to provide information about position, count, speed and direction. In the most basic terms, an encoder regardless of the type senses position, direction, speed or counts. Encoder will use motion over variety of technologies and translated into electrical signals. That signal is sent back to a controlling device such as plc or Arduino, or any other controller board, and is interrupted meaning scaled, to represent a value that will then be used in the program.

In this article, we will talk about the encoder in detail. I will explain different types of the encoder. In the end, I will share with your some project ideas with connection diagrams and Arduino codes explained.


Amazon Purchase Links:

12v Adaptor:

Arduino Uno

Arduino Nano

Mega 2560:

Rotary Encoder for Arduino:

Other Tools and Components:

Super Starter kit for Beginners

Digital Oscilloscopes

Variable Supply

Digital Multimeter

Soldering iron kits

PCB small portable drill machines

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Encoder technologies:

 Some of the technologies involved in encoders are:

  • Magnetic
  • Mechanical
  • Resistive
  • Optical

Optical is most widely used encoder motion translating technology.

Types of encoders:

There are different types of encoders

Incremental optical encoder:

This type of encoder use a beam of light that passes through a disk that has opaque lines in a specific pattern somewhat like a  spokes of wheel on the other side of the disk is a photo sensing device that will interpret the light based on the pattern on the disk, picture a shatter blocking and unblocking the light. The pulses of light are then converted to an electrical signal to send back to the processor, through the encoder output. Incremental encoders provide steady stream of high and low pulses that indicate the movement from one position to the next. The encoder does not indicate any specific position only the position is changed.



Absolute encoders:

Absolute encoder on the other hand indicates both the position and location of that position relative to the shaft rotation. The encoder provides a unique word or bit for each incremental rotation. Absolute encoders are the best choice for applications where exact positions to be known. It can be used in flood gate control, telescopes, cranes or valve positioning. It used magnetic or optical sensing technology. In optical encoders uses beam of light to produce a signal. While in magnetic encoders relies on alternating positive and negative magnetic pole.

Encoder

Basic element of optical increment encoder is a beam of light produced by led passes through transparent disk with radial opaque lines. When the light passes through opaque lines the sensor responds to the light by producing sinusoidal optical wave which is converted in square wave which is series of high and low pulses. This signal is then transfer to the controllers.

  In absolute encoder can be used in pitch control of the wind turbine blade angle to be adjusted according to the speed. Absolute encoders are of two types:

  • Single turn absolute encoder provides information for any increment within one shaft rotation.
  • Multi turn absolute encoders are provides information for multiple shaft rotation as many as half billion shaft rotation. Thus exact shaft rotation is known even after power interruption

Close loop applications of Encoder:

  • Servo or VFD control
  • Measuring
  • Counts

VFD control:

For VFD control we are running a pump on a VFD, to fill a tank full of a liquid. You are requesting a certain speed and want to verify that the pump VFD is at the requested speed. An encoder on the VFD may be used for feedback of the speed.

Measuring Process:

In this application you will need to cut some aluminium product to a particular size. We will pass a long roll, measuring hundreds of feet, of the aluminium sheet through a cutting mechanism. We need to determine the amount of aluminium fed, so that you cut the sheet to the proper size that will be used a manufacturing process. An encoder attached to the conveyor and reading the material that is feeding through your cutting assembly will indicate the length of the material that has been fed since the last cut. That feedback can be used to adjust the cutting blade to sever the length required.

Counts:

We have conveyor line that has bottles running on a conveyor that are counted by a photo eye sensor when entering the assembly. They have cap with an aluminium tamper proof foil on top that need to adhere to the bottle. Once the foil is sealed, the bottle will then move down the conveyor line and verified that it exited the cap sealing assembly via an exit photo sensor. Some of the requirements for the station are:

The same number of bottles entering the assembly must be exit in a “predetermined time frame”.

The bottle must not remain in front of an “entrance” or “exit” sensor.

The bottle must not be exposed to the inductive sealer longer then a predetermined amount of time.

We will make this assembly flexible enough to handle many types of bottles and entrance and exit sensor placement.


Rotary encoders:

Encoder is a communication device that controls the motion of the operating device. Encoders are used to translate rotatory and linear motion into a digital signal helping to determining the speed and position of the motor or other moving equipment. Basically an encoder accesses a measuring system for moving parts. There are two types of encoders:

  • Linear encoders
  • Rotatory encoder

 A rotary encoder is a type of position sensor which is used to that measures rotation on a shaft for determining the angular position of a rotating shaft. It transfers this rotation in series of pulses. These pulses control the controller attached to the encoder depending upon the shaft movement and in what direction it move.  According to the rotational movement it generates an electrical signal, either analog or digital. Rotary encoder measure the angular movement. It can measure both degree of movement and direction. Rotary encoder can be used as control and it is much more versatile than potentiometer. Rotary encoder can also be used as rotation sensors for motors and other devices. A rotary encoder collects data and provides feedback based on the rotation of the object or in other words a rotating device. Rotary encoders are sometimes called shaft encoders. This encoder type can convert an object position or motion based on the rotation of the shaft, depending on the measurement type used.  There are several methods of encoding output some of output can be incremental or absolute. It can use magnetic or optical sensors. Some devices even use lasers.

Absolute rotary encoders:

Absolute rotary encoders can measures angular positions.

Common type of rotary encoder is incremental which is also called quadrature or relative encoder. It can use two pulsed output signals to indicate both direction and degree of rotation.

Advantages of encoders:

  • Non-contact for high reliability
  • Very high precision
  • Robust design for application in harsh environment
  • Long service life and reduced service times
  • Compact design for many application

Difference between Rotary encoder and potentiometer:

Although rotary encoder looks a lot similar to the potentiometer but it works completely different. We used the potentiometer as a variable resistor. So we have one plus pin, one minus pin and resistor value pin. But the rotary encoders for example is used for directions so we can turn left, we can turn right and there is also a little switch so when we press the rotary encoder we will hear a little click. Because there is small switch on the bottom we can rotate infinitely to the right and infinitely to the left when we rotate it we will feel little clicks and every time we feel a click we can read movement to the left or right. In potentiometer we can rotate to the left until it stuck and to the left until is stuck. So we cannot infinitely rotate the knob of the potentiometer.

Working of Rotary encoder:

We get two waves while working on the rotary encoder. We get square wave A when we turn the rotary encoder clockwise and when we turn the rotary encoder anticlockwise we get square wave B.

They are used for all sorts of things in modern cars it is used for navigation system.

Rotary encoder testing:

Now to test the rotary encoder we will connect the encoder in bread board. Then connect the ground pin of the rotary encoder with the ground pin of the Arduino. The second pin of the rotary encoder with the 5V. The third pin is the switch which is activated when we press on the top we will connect this pin with the Arduino pin number 12. Now the fourth pin of the rotary encoder is the trigger which is connected with the pin number 3 of the Arduino. The clock pin of the rotary encoder is connected with the Arduino pin number 4.

We define the switch pin for when we press the rotary encoder which is connected with the pin number 12. The switch state is high and this look a little bit weird. The rotary encoder inverts this so the default state is high. When we press the rotary encoder it becomes low then we have a pin A and pin B which is connected with the 4 and 3 respectively. The current state of the pin A is low. In the setup we initialize the monitor 9600 baud rate and the pin mode of switch pin we have defined at pin 12. The pull up resistor is already inside the Arduino so we don’t need an extra one we just tell the Arduino that our switch pin 12, uses the internal pull up resistor saves us a resistor. In the loop we have separated two portion one is button portion and other is direction rotation. In the button part we it is a pretty straightforward we read the switch state whether the button is pressed with digitalRead() and we read this off with the switch pin If the state is low we press the button and if it is high it is in default state which is what we do here is when the switch state is low then the switch is pressed and we print that in our terminal. For the rotation direction we are going to read pin A and pin B. we read the pin A and store it as a current state of pin a in this variable. Then we want to know if there was any movement and we want to know for sure that it makes one step movement at least because otherwise we get a lot of false positives. So what we are doing over here we check if the last “A” state is low. So we check if that one was low and if the current state is high then we check the second state which is pin B if it is high then we rotate to the left. If we turn to the opposite direction then pin B is low and  the current state of A is high so then we print right. In last we store the current state of the pin A. once we have read and process this data of the digital pin the digital read on pin A. we can see the output on serial monitor.


Rotary Encoder Arduino Code:

int switchPin = 12;                        
int switchState = HIGH;                   
int pinA = 4;                              
int pinB = 3;                              
int pinAstateCurrent = LOW;               
int pinAStateLast = pinAstateCurrent;    
void setup() {
  Serial.begin (9600);                     

  pinMode (switchPin, INPUT_PULLUP);       
  
  pinMode (pinA, INPUT);                   
  pinMode (pinB, INPUT);                   
  
}

void loop() {

  // BUTTON
  switchState = digitalRead(switchPin);    // Read the digital value of the switch (LOW/HIGH)

  // If the switch is pressed (LOW), print message
  if (switchState == LOW) {
      Serial.println("Switch pressed");
  }
  

  // ROTATION DIRECTION
  pinAstateCurrent = digitalRead(pinA);    // Read the current state of Pin A
  
  // If there is a minimal movement of 1 step
  if ((pinAStateLast == LOW) && (pinAstateCurrent == HIGH)) 
{
    
    if (digitalRead(pinB) == HIGH) {      // If Pin B is HIGH
      Serial.println("Left");             // Print on screen
    } else {
      Serial.println("Right");            // Print on screen
    }
    
  }
  
  pinAStateLast = pinAstateCurrent;          
}

Rotary encoder and LCD with Arduino:

In this project we used rotary encoder to scroll to the menu. So first we will learn how to use rotary encoder?

How rotary encoder works?

How to select text in the lcd?

The rotary encoder detects the rotation steps, direction and also has push button inside. So it is the perfect component to scroll up and down the menu and also to select using the push button inside the rotary encoder we have the perimeter of copper connection the more connector we have the better is the precision of the encoder. We also have two connectors and we named it as clock and data pins. All of the internal connectors are connected to the ground and the clock and data pins has 10KΩ resistor. The base is not touching the copper connection. So the voltage at the output is 5V. When we start rotating the rotary encoder the clock output will touch one of the connector and the output at the click will be now ground but the data pin is still 5V. We till rotating until the data pin is ground. If the clock pin first touch the connector then it means that we are rotating clock wise and when the data pin first touch the connector then it means that we are rotating anticlockwise and each time it changes 5V to the ground we count first step but in the code we will save the initial state of the encoder and then detect any change in the base. So this is the vacant count step and detects the rotation direction. So when we rotating to the right we are increasing the steps and when we rotate to the left the steps are decreasing one important thing about the encoder is that the connector is greater than the pins and space between the connectors as well. So when at the certain movement both these can be feed to the metal connector because if not we could not be able to detect direction only steps can be detected.

Rotary Encoder Connection with Arduino:

Connect the clock pin with the digital pin 8 and data to the digital pin 9. Connect 10KΩ resistor with the digital pins and connect the ground pin of the Arduino to the rotary ground pin.

Encoder

Now in the code part we define the pins which we are using pin 8 and pin 9. We start the serial communication because we want to serial monitor the output. We read the state of the clock pin if the detected stated is not same as the last state then we will check the state of the data pin if it is not equal to clock pin then we are rotating to the right and if it is the same then we are rotating to the left by increasing or decreasing the counter value. Finally we print the value on the serial monitor.

Rotary Encoder Arduino Code:

#define clk 8
#define data 9
  
 int counter = 0; 
 int State;
 int LastState;  
 
 void setup() { 
   pinMode (clk,INPUT);
   pinMode (data,INPUT);   
   Serial.begin (9600); 
   LastState = digitalRead(clk);   
 } 
 void loop() { 
   State = digitalRead(clk); 
   if (State != LastState){     
     if (digitalRead(data) != State) { 
       counter ++;
     } else {
       counter --;
     }
     Serial.print("Position: ");
     Serial.println(counter);
   } 
   LastState = State; 
 }

Now we will connect LCD with the Arduino to make it simple we will used module with the lcd. Connect the ground pin of the module with the Arduino ground pin. Connect the clock pin with the analogue pin 5 and data pin with the analogue pin 4. Connect the 5V with the vcc.

Encoder

First we will add library for liquid crystal i2c then add the library to the Arduino code. Without this library the code will not work. We will define the slave address for this lcd. Init ()and backlight() functions will power up the lcd and back light. Then we clear the lcd and set the cursor to the first row and second column position and we write electronic clinic. Now we set the cursor to second row and write hello world.


Rotary Encoder Arduino Code:

/*

Download the Wire.h Library:

https://www.electroniclinic.com/arduino-libraries-download-and-projects-they-are-used-in-project-codes/

*/

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3f,20,4);  
void setup() {
  lcd.init();
  lcd.backlight();

}

void loop() { 
    
  lcd.clear();
  lcd.setCursor(2,0);
  lcd.print("ELECTRONIC CLINIC");
  lcd.setCursor(2,1);  
  lcd.print("hello  world");
  delay(3000);
}

Rotary encoder with the LCD and Arduino:

In this project we will display the output of the rotary encoder on the LCD. First we will connect the lcd with the Arduino:

To connect the lcd with the Arduino we will follow the following steps:

  • PIN1 or VSS of the lcd will be connected with the ground of Arduino
  • PIN2 or VDD of the lcd with the 5v of the Arduino
  • PIN3 or VEE of the lcd with the ground of the Arduino (gives maximum contrast best for a beginner)
  • PIN4 or RS (Register Selection) of the lcd with the PIN0 of the Arduinos
  • PIN5 or RW (Read/Write) of the lcd to the ground of the Arduino(puts LCD in read mode eases the communication for user)
  • PIN6 or E (Enable) of the lcd to PIN1 of Arduino
  • PIN11 or D4 of the lcd with the PIN8 of Arduino
  • PIN12 or D5 of the lcd with the PIN9 of Arduino
  • PIN13 or D6 of the lcd to PIN10 of Arduino
  • PIN14 or D7 of the lcd to PIN11 of Arduino

Now the lcd connections are complete we will now connect the rotary encoder with the Arduino:

  • Connect the Vin of the rotary to the 5V supply
  • Connect the clock pin of the rotary with the Arduino pin 3
  • Connect the data pin of the rotary encoder with ardunio pin 4
  • Connect the switch pin of the rotary encoder with Arduino pin 5
  • Connect the ground of the rotary encoder with Arduino ground

Encoder

Rotary Encoder and LCD Arduino Code:

int clk = 3;
int data  = 4;
int swt = 5;

int poutput;
int counter;

#include <LiquidCrystal.h>  //Default Arduino LCD Librarey is included 

const int rs = 0, en = 1, d4 = 8, d5 = 9, d6 = 10, d7 = 11; //in this section we define the pin of the lcd with the Arduino
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  lcd.begin(16, 2); //Initialise 16*2 LCD

  lcd.print(" Rotary Encoder "); //Intro Message line 1
  lcd.setCursor(0, 1);
  lcd.print("  With Arduino  "); //Intro Message line 2

  delay(2000);
  lcd.clear();

//pin Mode declaration 
  pinMode (clk, INPUT);
  pinMode (data, INPUT);
  pinMode (swt, INPUT);

  poutput = digitalRead(clk); //Read the initial state of the clock 
}

void loop() {
   
   if (digitalRead(clk) != poutput)
   { 
     if (digitalRead(data) != poutput) 
     { 
       counter=counter+1;
       lcd.clear();  
       lcd.print(counter);
       lcd.setCursor(0, 1);  
       lcd.print("Clockwise");
     } 
     else 
     {
       counter=counter-1;
       lcd.clear();  
       lcd.print(counter);
       lcd.setCursor(0, 1);  
       lcd.print("Anti - Clockwise");
     }
   }

   poutput = digitalRead(clk);

   if (digitalRead(swt) == 0)
   {
     lcd.clear();  
     lcd.setCursor(0, 1);  
     lcd.print("Switch pressed");
   }
}

Rotary encoder with the LEDs:

In this project we will used led to show the directions of the rotary encoder for example in this project we use two leds red and green when the rotary encoder will rotate in clockwise one led will be turn on and when the rotary encoder will rotate anticlockwise the other will be turn on. For counter clockwise we use red led and for clock we use green led.

Connect 5V of the Arduino with the rotary encoder vcc. Ground of the rotary encoder with the ground of the Arduino. Connect the clock pin of the rotary encoder with the digital pin number 4 of the Arduino and data pin of the rotary encoder with the Arduino digital pin 5. Connect 220Ω resistor with the anode of the green led and connect with the digital pin 8. Similarly Connect 220Ω resistor with the anode of the red led and connects with the digital pin 9. Connect the cathode of both led with the ground.

Encoder



Rotary Encoder Arduino Code

// Rotary Encoder Inputs
 #define clk 4
 #define dat 5
 
 // LED Outputs
 #define ledCW 8
 #define ledACW 9
 
 int counter = 0; 
 int cStateCLK;
 int pStateCLK; 
 
 String encdir ="";
 
 void setup() { 
   
   // Set encoder clock and data pins as inputs  
   pinMode (clk,INPUT);
   pinMode (dat,INPUT);
   
   // Set green and red LED pins as outputs
   pinMode (ledCW,OUTPUT);
   pinMode (ledACW,OUTPUT);
   
   // Setup Serial Monitor to watch the output
   Serial.begin (9600);
   
   // Read the initial state of inputCLK and Assign to previousStateCLK variable
   pStateCLK = digitalRead(clk);
 
 } 
 
 void loop() { 
  
  // Read the current state of inputCLK of the rotary encoder
   cStateCLK = digitalRead(clk);
    
   if (cStateCLK != pStateCLK){ 
       
     if (digitalRead(dat)!=cStateCLK)
     {
       counter --;
       encdir ="CCW";
      //the green led will off and red led will be turn on
       digitalWrite(ledCW, LOW);
       digitalWrite(ledACW, HIGH);
     }
       
      else {
       // Encoder is rotating clockwise
       counter ++;
       //endir will store the state of the rotary encoder
       encdir ="CW";
       //the red led will be off and green led will be turn on
       digitalWrite(ledCW, HIGH);
       digitalWrite(ledACW, LOW);
       
      }
     Serial.print("Direction: ");
     Serial.print(encdir);
     Serial.print(" -- Value: ");
     Serial.println(counter);
   } 
   // Update previousStateCLK with the current state
   pStateCLK = cStateCLK; 
 }

Servo motor control with Rotary encoder and Arduino:

In this project we control servo motor through rotary encoder. When we rotate the rotary encoder clockwise the servo motor will be rotate clockwise similarly when we rotate the rotary encoder anticlockwise the servomotor will rotate anticlockwise. First we will connect the rotary encoder with the Arduino such that connect the vin of the rotary encoder with the 5V of Arduino connect the ground of the rotary encoder with the ground of the Arduino. Connect the data pin of the rotary encoder with the digital pin 4 of the Arduino and connect the clock pin of the rotary encoder with digital pin 3 and switch pin with the digital pin 5.

Now we will connect the servo motor with the Arduino .

Connect the vin of the servo motor with 3.3V of the Arduino.

Connect the ground of the servo motor with the Arduino ground.

Connect the signal pin of the servo motor with the digital pin of the Arduino.

Encoder

Rotary Encoder Arduino Code Explanation:

First we will import the servo motor library in the Arduino code if we not include the library the code will not work. Then define the clk and data pin at 3 and 4 respectively. Define the switch pin at 5. We will set the counter value at 90. State and lstate variables are used to store the state. For servo motor we use s variable. In setup function we define the clk,sw and data as the input pins and  attach servo motor at pin 9. Serial begin function is used to monitor the output on the screen. We will read the state of the clock pin and store at in the lstate variable. In the loop section we will read the state of the data and store at in the state variable.  Constrain function limit the value of the counter between 1 and 180. Write function will apply the counter value on the servo motor.


Rotary Encoder Arduino Code:

/*

You will need the Servo Library:

https://www.electroniclinic.com/arduino-libraries-download-and-projects-they-are-used-in-project-codes/

*/

#include <Servo.h>
#define clk 3
#define data 4
#define sw 5
int counter=90;
int state;
int lstate;
Servo s;
void setup()
{
  pinMode(clk,INPUT);
  pinMode(data,INPUT);
  
  pinMode(sw,INPUT);
  s.attach(9);
  Serial.begin(9600);
  lstate=digitalRead(clk);  
}
void loop()
{
state= digitalRead(clk);

if (state!=lstate)
{
  if(digitalRead(data)!= state)
  {
    counter=counter+3;
    counter= constrain(counter,1,180);
    
  }
  else
  {
     counter=counter-3;
    counter= constrain(counter,1,180);
  }
  Serial.println(counter);
  s.write(counter);
}
lstate=state;
}

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

One Comment

  1. In the famous words of Henry Gibson, Very Interesting, taken from old Rowan and Martin’s laugh in shows which I used to watch as a kid. I’m now retired and have always been into electronics, I went to tech school for it in 79/80 but didn’t follow it as much as I should have. Now that I have too much time and not enough money, I’m back into it and way behind in technical knowledge. At the moment, I’m trying to assemble a solar tracking system using a 328 with 2 H-bridges. I also want to include an absolute position sensing portion to control the 2 axis’ of this tracking system and linear actuators. I could sure use some help with the code and maybe some with the electrical parts. I have a lot of the controller circuitry figured out and assembled at the moment. Not sure if it will work but it looks good to me so far. I built the Arduino clone board and the h bridges as a stacked assembly on proto boards for the first unit. I’m not an EE, I have been an electrician for a while, done a lot of work with electrical and electronics over the years. I used to work with renewable energy, I lived off the grid for many years and never was without power from my solar and wind system, did work on a 65kw commercial turbine for a while and have done a lot of residential and some commercial wiring, some of it got pretty complicated. I have designed a few circuits for stuff and now it is out there in the world not by my choice though, it was hacked from my computer and now I don’t have the business I was trying to establish with a company in Okl. I did the design work for. Anyway I’d like to correspond with you about things.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button