//Encoder KY-040
/*
#include <LiquidCrystal_I2C.h>
#define CLK 2
#define DT 3
#define SW 4
/*PINOS
ENCODER:
2 = CLK (Clock)
3 = DT (Digital)
4 = SW (Switch)
DISPLAY LCD
A5 = SCL
A4 = SDA
*/
/*
int coluna = 20;
int linha = 4;
const int endereco = 0x27;
LiquidCrystal_I2C lcd(endereco, coluna, linha);
*/
// Initialization of the needed variables<br />
int Counter = 0;
boolean Richtung;
int Pin_clk_Letzter;
int Pin_clk_Aktuell;
// Definition of the input-pins
int pin_clk = 2;
int pin_dt = 3;
int button_pin = 4;
void setup()
{
// Initialization of the input-pins...
pinMode (pin_clk,INPUT);
pinMode (pin_dt,INPUT);
pinMode (button_pin,INPUT);
// ...and activating of their pull up resistors
digitalWrite(pin_clk, true);
digitalWrite(pin_dt, true);
digitalWrite(button_pin, true);
// Initial reading of the Pin_CLK
Pin_clk_Letzter = digitalRead(pin_clk);
Serial.begin(115200);
}
// The program checks, which of the status pins have changed first
void loop()
{
// Reading of the current status
Pin_clk_Aktuell = digitalRead(pin_clk);
// Check for a Change
if(Pin_clk_Aktuell != Pin_clk_Letzter)
{
if(digitalRead(pin_dt) != Pin_clk_Aktuell)
{
// Pin_CLK has changed first
Counter ++;
Richtung = true;
}
else
{
// Else Pin_DT changed first
Richtung = false;
Counter--;
}
Serial.println ("Rotation detected: ");
Serial.println ("Rotation detected: ");
Serial.print ("Rotational direction: ");
if(Richtung)
{
Serial.println ("Clockwise");
}
else
{
Serial.println("Counterclockwise");
}
Serial.print("Current position: ");
Serial.println(Counter);
Serial.println("------------------------------");
}
// Preparation for the next run:
// The current value will be the last value for the next run.
Pin_clk_Letzter = Pin_clk_Aktuell;
// Reset funciton to save the current position
if (!digitalRead(button_pin) && Counter!=0)
{
Counter = 0;
Serial.println("Position resetted");
}
}