#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include "icons.h"
#define TFT_DC 2
#define TFT_CS 15
#define CLK_PIN 16
#define DT_PIN 17
#define SW_PIN 5
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
float rotaryMax = 3;
float rotaryMin = 0;
float rotaryStep = 1;
bool lastClkState = LOW;
float rotaryCounter = 0;
enum MenuState { MAIN_MENU, SUB_MENU };
MenuState currentMenu = MAIN_MENU;
int lastSelection = -1; // Track the previously selected item
void drawMenuItem(const char* text, int index, bool selected) {
int menuY = index * 50;
int itemOffX = 20;
int itemOffY = 10;
if (selected) {
tft.fillRect(0, menuY, ILI9341_TFTWIDTH, 50, ILI9341_ORANGE);
tft.setTextColor(ILI9341_BLACK);
} else {
tft.fillRect(0, menuY, ILI9341_TFTWIDTH, 50, ILI9341_BLACK);
tft.setTextColor(ILI9341_WHITE);
}
tft.setCursor(0 + itemOffX, menuY + itemOffY);
tft.println(text);
}
void showMenu(bool clearScreen) {
const char* items[] = {"Item 1", "Item 2", "Item 3", "Sub-menu"};
const char* subItems[] = {"Sub-item 1", "Sub-item 2", "Back"};
int lenItems = sizeof(items) / sizeof(items[0]);
int lenSubItems = sizeof(subItems) / sizeof(subItems[0]);
const char** currentItems;
int currentLen;
if (currentMenu == MAIN_MENU) {
currentItems = items;
currentLen = lenItems;
} else if (currentMenu == SUB_MENU) {
currentItems = subItems;
currentLen = lenSubItems;
}
if (clearScreen) {
tft.fillScreen(ILI9341_BLACK); // Clear the screen before drawing the menu
}
for (int i = 0; i < currentLen; i++) {
drawMenuItem(currentItems[i], i, (rotaryCounter == i));
}
lastSelection = (int)rotaryCounter;
}
void setup() {
tft.begin();
tft.setRotation(1);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(4);
tft.println("Ready");
pinMode(SW_PIN, INPUT_PULLUP);
pinMode(CLK_PIN, INPUT);
pinMode(DT_PIN, INPUT);
lastClkState = digitalRead(CLK_PIN);
showMenu(true);
}
void loop() {
if (digitalRead(SW_PIN) == LOW) {
delay(100); // debounce
if (currentMenu == MAIN_MENU && rotaryCounter == 3) {
currentMenu = SUB_MENU;
rotaryCounter = 0;
rotaryMax = 2;
rotaryMin = 0;
showMenu(true);
} else if (currentMenu == SUB_MENU && rotaryCounter == 2) {
currentMenu = MAIN_MENU;
rotaryCounter = 0;
rotaryMax = 3;
rotaryMin = 0;
showMenu(true);
}
}
bool newClkState = digitalRead(CLK_PIN);
if (newClkState != lastClkState && newClkState == HIGH) {
if (digitalRead(DT_PIN)) {
rotaryCounter -= rotaryStep;
} else {
rotaryCounter += rotaryStep;
}
if (rotaryCounter > rotaryMax) rotaryCounter = rotaryMin;
if (rotaryCounter < rotaryMin) rotaryCounter = rotaryMax;
showMenu(false); // Update the screen without clearing it
}
lastClkState = newClkState;
}