/*
Rotary Encoder Demo
rot-encode-demo.ino
Demonstrates operation of Rotary Encoder
Displays results on Serial Monitor
DroneBot Workshop 2019
https://dronebotworkshop.com
*/
// Rotary Encoder Inputs
#define inputCLK 5
#define inputDT 4
// LED Outputs
#define ledCW 8
#define ledCCW 9
#define Ledpin 2
int counter = 0;
int currentStateCLK;
int previousStateCLK;
String encdir ="";
void setup() {
// Set encoder pins as inputs
pinMode (inputCLK,INPUT_PULLUP);
pinMode (inputDT,INPUT_PULLUP);
// Set LED pins as outputs
pinMode (ledCW,OUTPUT);
pinMode (ledCCW,OUTPUT);
pinMode (Ledpin,OUTPUT);
// Setup Serial Monitor
Serial.begin (9600);
// Read the initial state of inputCLK
// Assign to previousStateCLK variable
previousStateCLK = digitalRead(inputCLK);
}
void loop() {
// Read the current state of inputCLK
currentStateCLK = digitalRead(inputCLK);
// If the previous and the current state of the inputCLK are different then a pulse has occured
if (currentStateCLK != previousStateCLK){
// If the inputDT state is different than the inputCLK state then
// the encoder is rotating counterclockwise
if (digitalRead(inputDT) != currentStateCLK) {
counter --;
if (counter<0){
counter = 0;
}
encdir ="CCW";
digitalWrite(ledCW, LOW);
digitalWrite(ledCCW, HIGH);
} else {
// Encoder is rotating clockwise
counter ++;
if (counter>30){
counter = 30;
}
encdir ="CW";
digitalWrite(ledCW, HIGH);
digitalWrite(ledCCW, LOW);
}
switch (counter) {
case 0:
Serial.println("Landsort");
break;
case 2:
Serial.println("Öland södra udde");
digitalWrite(Ledpin, HIGH);
delay (700);
digitalWrite(Ledpin, LOW);
delay(1400);
digitalWrite(Ledpin, HIGH);
delay(700);
digitalWrite(Ledpin, LOW);
delay(5000);
break;
case 4:
Serial.println("Morups tånge");
break;
case 6:
Serial.println("Häradskär");
break;
case 8:
Serial.println("Kullen");
break;
case 10:
Serial.println("Hallands väderö");
break;
case 12:
Serial.println("Gotska sandön");
break;
case 14:
Serial.println("Pite-Rönnskär");
break;
case 16:
Serial.println("Bergudden");
break;
case 18:
Serial.println("Hjortens udde");
break;
case 20:
Serial.println("Stavik");
break;
case 22:
Serial.println("Svartklubben");
break;
case 24:
Serial.println("Grönskär");
break;
case 26:
Serial.println("Bönan");
break;
case 28:
Serial.println("Vinga");
break;
case 30:
Serial.println("Örskär");
break;
}
Serial.print("Direction: ");
Serial.print(encdir);
Serial.print(" -- Value: ");
Serial.println(counter);
}
// Update previousStateCLK with the current state
previousStateCLK = currentStateCLK;
}