// KY-040 Rotary Encoder Example
// Taken from: https://docs.wokwi.com/parts/wokwi-ky-040
// Copyright (C) 2021, Uri Shaked
#include <Stepper.h>
const int stepsPerRevolution = 20; // change this to fit the number of steps per revolution
// for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
#define ENCODER_CLK 2
#define ENCODER_DT 3
void setup() {
Serial.begin(115200);
// set the speed at 60 rpm:
myStepper.setSpeed(300);
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
}
int lastClk = HIGH;
void loop() {
int newClk = digitalRead(ENCODER_CLK);
if (newClk != lastClk) {
// There was a change on the CLK pin
lastClk = newClk;
int dtValue = digitalRead(ENCODER_DT);
if (newClk == LOW && dtValue == HIGH) {
myStepper.step(stepsPerRevolution);
Serial.println("Rotated clockwise ⏩");
}
if (newClk == LOW && dtValue == LOW) {
myStepper.step(-stepsPerRevolution);
Serial.println("Rotated counterclockwise ⏪");
}
}
}
/*
// step one revolution in one direction:
Serial.println("clockwise");
myStepper.step(stepsPerRevolution);
delay(500);
// step one revolution in the other direction:
Serial.println("counterclockwise");
myStepper.step(-stepsPerRevolution);
delay(500);
*/