// Definition of the constants
#define SW_ENCODER 13
#define DT_ENCODER 12
#define CLK_ENCODER 11
// Definition of global variables
int counter_encoder = 0;
void analyse_encoder ()
{
// Definition of static variables
static bool clkState;
static bool clkLastState = true;
// Reads the state of the clk input
clkState = digitalRead(CLK_ENCODER);
// Check if the previous and the current state of the clk input are different
if (clkState == false and clkLastState == true)
{
// Check if the dt input state is different to the clk input state (encoder is rotating clockwise)
if (digitalRead(DT_ENCODER) != clkState)
{
counter_encoder ++;
}
else
{
counter_encoder --;
}
}
// Updates the previous state of the clk input with the current state
clkLastState = clkState;
}
// Setup of the programme: Is executed once during the start of the microcontroller
void setup()
{
// Initialising serial communication
Serial.begin(9600);
// Defining the encoder pins as pullup inputs
pinMode(SW_ENCODER, INPUT_PULLUP);
pinMode(DT_ENCODER, INPUT_PULLUP);
pinMode(CLK_ENCODER, INPUT_PULLUP);
}
void loop()
{
analyse_encoder();
Serial.print(counter_encoder);
}