MisterBotBreak
Published

How to Use a Rotary Encoder

In this little project, I'll show how to use a rotary encoder.

BeginnerProtip1 hour12,780
How to Use a Rotary Encoder

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
Male/Female Jumper Wires
Male/Female Jumper Wires
×1
Rotary Encoder with Push-Button
Rotary Encoder with Push-Button
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Code

Rotary encoder

Arduino
int val; 
int PinCLK = 4;
int PinDT = 5;
int PinSW = 0;
static long encoderPos = -1;    // Au 1er démarrage, il passera à 0
int PinCLKLast = LOW;
int nbPas = 20;                 // Résolution de l'encodeur
int n = LOW;

void setup() { 
  pinMode (PinCLK,INPUT);
  pinMode (PinDT,INPUT);
  pinMode (PinSW,INPUT);
  Serial.begin (9600);
} 

void loop() { 
   if (!(digitalRead(PinSW))) {      
     encoderPos = 0;
     
   }
   
   n = digitalRead(PinCLK);
   
   if ((PinCLKLast == LOW) && (n == HIGH)) {
     
     if (digitalRead(PinDT) == LOW) {
       encoderPos--;
       if ( encoderPos < 0 ) {
         encoderPos = nbPas;
       }
     } else {
       encoderPos++;
       if ( encoderPos > ( nbPas - 1 ) ) {
         encoderPos = 0;
       }
     }
     Serial.print (encoderPos); 
     Serial.print(", angle "); 
     Serial.println( abs ( encoderPos * ( 360 / nbPas ) ) );
     
   } 
   PinCLKLast = n;
 }

Credits

MisterBotBreak

MisterBotBreak

48 projects • 149 followers
I love electronics and cats :D !

Comments