Lisleapex Blog
Published © CERN-OHL

How Rotary Encoders Work and Interface With Arduino

We are surrounded by rotary encoders without even realizing it, as they are used in many everyday items.

BeginnerWork in progress2 hours103
How Rotary Encoders Work and Interface With Arduino

Things used in this project

Hardware components

Rotary Encoder with Push-Button
Rotary Encoder with Push-Button
×1
SG90 Micro-servo motor
SG90 Micro-servo motor
×1
Rotary potentiometer (generic)
Rotary potentiometer (generic)
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

connecting_the_rotary_encoder_to_the_arduino_ARfCIaofPo.jpg

Code

Untitled file

Arduino
// Include the Servo Library
#include <Servo.h>
 
// Rotary Encoder Inputs
#define CLK 2
#define DT 3
 
Servo servo;
int counter = 0;
int currentStateCLK;
int lastStateCLK;
 
void setup() {
 
	// Set encoder pins as inputs
	pinMode(CLK,INPUT);
	pinMode(DT,INPUT);
	
	// Setup Serial Monitor
	Serial.begin(9600);
	
	// Attach servo on pin 9 to the servo object
	servo.attach(9);
	servo.write(counter);
	
	// Read the initial state of CLK
	lastStateCLK = digitalRead(CLK);
}
 
void loop() {
        
	// Read the current state of CLK
	currentStateCLK = digitalRead(CLK);
	
	// If last and current state of CLK are different, then pulse occurred
	// React to only 1 state change to avoid double count
	if (currentStateCLK != lastStateCLK  && currentStateCLK == 1){
		
		// If the DT state is different than the CLK state then
		// the encoder is rotating CCW so decrement
		if (digitalRead(DT) != currentStateCLK) {
			counter --;
			if (counter<0)
				counter=0;
		} else {
			// Encoder is rotating CW so increment
			counter ++;
			if (counter>179)
				counter=179;
		}
		// Move the servo
		servo.write(counter);
		Serial.print("Position: ");
		Serial.println(counter);
	}
	
	// Remember last CLK state
	lastStateCLK = currentStateCLK;
}

Credits

Lisleapex Blog
26 projects • 0 followers
Fast Delivery of High-Quality Electronic Components
Contact

Comments

Please log in or sign up to comment.