Rotary Encoder of KY040 with Arduino

Status
Not open for further replies.

imranahmed

Advanced Member level 3
Joined
Dec 4, 2011
Messages
822
Helped
3
Reputation
6
Reaction score
3
Trophy points
1,298
Location
Karachi,Pakistan
Visit site
Activity points
6,533
Please let me know that I want to interface rotary encoder with arduino

but I tried some programs but when I rotate encoder then some readings are missed

Code:
#include <Arduino.h>

// -----------------------------------------------------------------------------
// constants

const int                                 PinCLK   = 2;     // Used for generating interrupts using CLK signal
const int                                 PinDT    = 3;     // Used for reading DT signal
const int                                 PinSW    = 4;     // Used for the push button switch

// -----------------------------------------------------------------------------
// global vars

volatile int                             virtualPosition    = 0;

// -----------------------------------------------------------------------------
// forward decls

void isr();
void loop();
void setup();

// -----------------------------------------------------------------------------
// Interrupt service routine is executed when a HIGH to LOW transition is detected on CLK

void isr ()  {
    if (!digitalRead(PinDT))
        virtualPosition = virtualPosition + 1;
    else
        virtualPosition = virtualPosition - 1;
    } // isr

// -----------------------------------------------------------------------------

void setup() {
    Serial.begin(9600);

    pinMode(PinCLK,INPUT);
    pinMode(PinDT, INPUT);
    pinMode(PinSW, INPUT);

    attachInterrupt(0, isr, FALLING);   // interrupt 0 is always connected to pin 2 on Arduino UNO

    Serial.println("Start");

    } // setup

// -----------------------------------------------------------------------------

void loop() {

    int lastCount = 0;

    while (true) {
        if (!(digitalRead(PinSW))) {        // check if pushbutton is pressed
            virtualPosition = 0;            // if YES, then reset counter to ZERO
            while (!digitalRead(PinSW)) {}  // wait til switch is released
            delay(10);                      // debounce
            Serial.println("Reset");        // Using the word RESET instead of COUNT here to find out a buggy encoder
            }
        if (virtualPosition != lastCount) {
            lastCount = virtualPosition;
            Serial.print("Count=");
            Serial.println(lastCount);
            }
        } // while
    } //loop
 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…