//#include <Keyboard.h>
const int encoderClk = 2; // Rotary encoder pin 1
const int encoderDT = 3; // Rotary encoder pin 2
const int buttonPin = 4; // Rotary encoder button pin
int lastState;
int currentState;
int section = 0;
const int numSections = 7;
const char* sectionNames[] = {"Text Entry", "Types", "Instruments", "Styles", "Banks", "User", "Blank Section"};
#define KEY_TAB "KEY_TAB"
#define KEY_LEFT_SHIFT "KEY_LEFT_SHIFT"
#define KEY_RETURN "KEY_RETURN"
struct kbt {
void begin();
void write(String aKey);
void release(String aKey);
} Keyboard;
void kbt::begin() {}
void kbt::write(String aKey) {
Serial.print(aKey + " ");
}
void kbt::release(String aKey) {
Serial.print(aKey + "_released ");
}
void setup() {
Serial.begin(115200);
Keyboard.begin();
pinMode(encoderClk, INPUT_PULLUP);
pinMode(encoderDT, INPUT_PULLUP);
pinMode(buttonPin, INPUT_PULLUP);
lastState = digitalRead(encoderClk);
}
void loop() {
// Read the current state of the rotary encoder
int state = digitalRead(encoderClk);
if (state != lastState) {
lastState = state; // moved here from the wrong place ...
if (!state && digitalRead(encoderDT) == HIGH) {
section++;
Serial.println("section++\t"+String(section));
if (section >= numSections) { section = 0; }
if (section == 6) {
// Send 5 tabs for Blank Section
for (int i = 0; i < 5; i++) {
Keyboard.write(KEY_TAB);
}
} else {
Keyboard.write(KEY_TAB);
}
Serial.print("Section: ");
Serial.println(sectionNames[section]);
delay(100); // debounce delay
} else {
if (!state && digitalRead(encoderDT) == LOW){
section--;
Serial.println("section--\t"+String(section));
if (section < 0) {
section = numSections - 1;
}
if (section == 6) {
// Send 5 shift+tabs for Blank Section
Keyboard.write(KEY_LEFT_SHIFT);
for (int i = 0; i < 5; i++) {
Keyboard.write(KEY_TAB);
}
Keyboard.release(KEY_LEFT_SHIFT);
} else {
Keyboard.write(KEY_LEFT_SHIFT);
Keyboard.write(KEY_TAB);
Keyboard.release(KEY_LEFT_SHIFT);
Keyboard.release(KEY_TAB);
}
Serial.print("Section: ");
Serial.println(sectionNames[section]);
delay(100); // debounce delay
}
}
}
//lastState = state; // Wrong place here!!!! Should be inside the "if (state != lastState))
// Check if the encoder button has been pressed
if (digitalRead(buttonPin) == LOW) {
Keyboard.write(KEY_RETURN);
Serial.println("Enter");
delay(500); // debounce delay
Keyboard.release(KEY_RETURN);
}
}