I have been working with Chat GPT trying to get it to write some code for an Encoder to cycle through a set of seven sections, sending out a series of Tabs each time it detents to the right, and a series of Shift+Tabs every time it detents to the left. Here is the code it has written:
#include <Keyboard.h>
const int encoderPin1 = 2; // Rotary encoder pin 1
const int encoderPin2 = 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"};
void setup() {
Keyboard.begin();
pinMode(encoderPin1, INPUT_PULLUP);
pinMode(encoderPin2, INPUT_PULLUP);
pinMode(buttonPin, INPUT_PULLUP);
lastState = digitalRead(encoderPin1);
}
void loop() {
// Read the current state of the rotary encoder
int state = digitalRead(encoderPin1);
if (state != lastState) {
if (digitalRead(encoderPin2) != state) {
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 {
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;
// 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);
}
}
The code is working ok for the right turns, meaning: it is sending out Tabs as it should. But for whatever reason, it will not send out the Shift+Tabs when the encoder turns to the left. It just continues cycling through the sections, moving from left to right, even though it should at that point cycle by moving from right to left.
In looking at the code, it's clear to me that the lines germane to this operation are lines 54-59. They look like they should work-all kind of standard fare. But no matter what, the code is not working as it should when the encoder is turned to the left.
Can anybody out there figure out what's wrong with the code, and a possible solution?
Thanks for the help.
Clay