/* KY-040 Rotary Encoder Counter
Rotate clockwise to count up, counterclockwise to counter done.
Press to reset the counter.
Copyright (C) 2021, Uri Shaked
*/
#include <AccelStepper.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
#define ENCODER_CLK 2
#define ENCODER_DT 3
#define ENCODER_SW 4
#define STEP_PIN 6
#define DIR_PIN 5
#define motorInterfaceType 1
const int stepsPerRevolution =200; // liczba kroków na pełny obrot
AccelStepper myStepper(motorInterfaceType, STEP_PIN, DIR_PIN );
int counter = 0;
void setup() {
// Initialize LCD
lcd.init();
lcd.backlight();
// Initialize encoder pins
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
pinMode(ENCODER_SW, INPUT_PULLUP);
myStepper.setMaxSpeed(1000);
myStepper.setAcceleration(500);
attachInterrupt(digitalPinToInterrupt(ENCODER_CLK), readEncoder, FALLING);
}
void readEncoder() {
int dtValue = digitalRead(ENCODER_DT);
//----------------------------------------------------
if (dtValue == HIGH) {
counter++; // Clockwise
digitalWrite(5, HIGH);
myStepper.move(1);
myStepper.run();
}
//--------------------------------------------------//
if (dtValue == LOW) {
counter--; // Counterclockwise
digitalWrite(5, LOW);
myStepper.move(-1);
myStepper.run();
}
}
// Get the counter value, disabling interrupts.
// This make sure readEncoder() doesn't change the value
// while we're reading it.
int getCounter() {
int result;
noInterrupts();
result = counter;
interrupts();
return result;
}
//------------------------------------------------------//
void resetCounter() {
noInterrupts();
counter = 0; // Reset licznika
interrupts();
}
//-----------------------------------------------------//
void loop() {
lcd.setCursor(3, 0);
lcd.print("Counter:");
lcd.setCursor(7, 1);
lcd.print(getCounter()*1.8);
lcd.print(" ");
if (digitalRead(ENCODER_SW) == LOW) {
resetCounter();
}
}