Skip to main content
Topic: Arduino Rotary Encoder Project (Read 2844 times) previous topic - next topic

Arduino Rotary Encoder Project

Hello, I'm attempting my first Arduino project from scratch and to learn I want to get the basic components working.
Now I don't get a reading of the rotary encoder on the Arduino IDE serial monitor.
rotary encoder is KY-040 on Arduino Mega.
Code: [Select]
int messungPin1 = LOW;
int messungPin1Alt = LOW;
int encoderWert = 0;

 void setup() {
 pinMode(51, INPUT); //CLK
 pinMode(52, INPUT); //DT
 Serial.begin(9600);
 }

 void loop() {
 messungPin1 = digitalRead(3);
 if ((messungPin1 == HIGH) && (messungPin1Alt == LOW)) {
 if (digitalRead(4) == HIGH) {
 encoderWert++;
 } else {
 encoderWert--;
 }
 Serial.println (encoderWert);
 }
 messungPin1Alt = messungPin1;
 }

Re: Arduino Rotary Encoder Project

Reply #1
Code: [Select]
/*     Arduino Rotary Encoder Tutorial
 *     
 *  by Dejan Nedelkovski, [url=http://www.HowToMechatronics.com]How To Mechatronics[/url]
 * 
 */
 
 #define outputA 6
 #define outputB 7
 int counter = 0;
 int aState;
 int aLastState; 
 void setup() {
   pinMode (outputA,INPUT);
   pinMode (outputB,INPUT);
  
   Serial.begin (9600);
   // Reads the initial state of the outputA
   aLastState = digitalRead(outputA);  
 }
 void loop() {
   aState = digitalRead(outputA); // Reads the "current" state of the outputA
   // If the previous and the current state of the outputA are different, that means a Pulse has occured
   if (aState != aLastState){    
     // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
     if (digitalRead(outputB) != aState) {
       counter ++;
     } else {
       counter --;
     }
     Serial.print("Position: ");
     Serial.println(counter);
   }
   aLastState = aState; // Updates the previous state of the outputA with the current state
 }

this should work. Just define your pins at the top.

I got it here
How Rotary Encoder Works and How To Use It with Arduino - HowToMechatronics

I've checked it on my Uno test board and its sending feedback, just make sure to set the serial monitors baud rate to 9600 as its defined in the code.

Re: Arduino Rotary Encoder Project

Reply #2
I see the problem with your code. You defined the state of the pins. You should have them as reading their state compared to their previous state.
You defined them as always low.
They should look at there previous state, so say low.....
And then if it's changed to high that tells them where the rotor is now, depending on which pin changed state...