#define pinCLK 1 // CLK pin connected to GPIO 1 #define pinDT 2 // DT pin connected to GPIO 2 #define pinSW 3 // SW pin connected to GPIO 3 int count = 0; // Var to know how many clicks occured (increment clockwise and decrement counter_clockwise) int previousStateSW; // Var to memorize previous SW state to compare it with actual state int previousStateCLK; // Var to memorize previous CL state to compare it with actual state void setup() { Serial.begin(9600); pinMode(pinSW, INPUT_PULLUP); // INPUT_PULLUP to avoid 'floating' pinMode(pinDT, INPUT); pinMode(pinCLK, INPUT); previousStateSW = digitalRead(pinSW); // initial value for SW previousStateCLK = digitalRead(pinCLK); // initial value for CLK delay(200); // delay to stabilize signal before the loop } void loop() { int actualStateCLK = digitalRead(pinCLK); // reading CLK value int actualStateDT = digitalRead(pinDT); // reading DT value int actualStateSW = digitalRead(pinSW); // reading SW value // ************************* // Push Button verification // ************************* if(actualStateSW != previousStateSW) { // Checking if SW state has changed previousStateSW = actualStateSW; // Save new state if(actualStateSW == LOW) Serial.println(F("SW Button pushed")); // Display State on serial monitor else Serial.println(F("SW Button released")); delay(10); // Delay to avoid rebounce } // *************************** // Rotary encoder verification // *************************** if (actualStateCLK != previousStateCLK) { delayMicroseconds(200); // Debounce delay if (digitalRead(pinCLK) == actualStateCLK) { // Check if the CLK signal has settled previousStateCLK = actualStateCLK; if(actualStateCLK == LOW) { if(actualStateCLK != actualStateDT) { // comparing CLK and DT, if they're different, direction is counter-clockwise count++; // decrement counter Serial.println(F("clockwise")); // Display value on Serial Monitor // Serial.println(count); } else { // when CLK and DT are similar, direction is clockwise count--; // increment counter Serial.println(F("counter-clockwise")); // Display value on Serial Monitor // Serial.println(count); } } } } }