#include "SPI.h"
#include <Wire.h>
#include <Adafruit_GFX.h>
#include "Adafruit_SH1106.h"
#include <Encoder.h>
//#define SCREEN_WIDTH 128
//#define SCREEN_HEIGHT 64
//#define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin)
//Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define OLED_RESET 4
Adafruit_SH1106 display(OLED_RESET);
Encoder encoder(A2, A3); // Change the pins based on your wiring
const int switchPin = 4; // Connect the switch pin to D4
int menuIndex = 0;
int maxMenuIndex = 7; // Adjust the number of menu items accordingly
int lastMenuIndex = -1;
int visibleItems = 4; // Number of visible menu items on the screen
int scrollOffset = 0;
void setup() {
pinMode(switchPin, INPUT_PULLUP);
display.begin(SH1106_SWITCHCAPVCC, 0x3C);
//display.clearDisplay();
//display.setTextSize(1);
//display.setTextColor(WHITE);
//display.setCursor(0, 5);
display.display(); // Clear the display buffer
delay(2000); // Pause for 2 seconds
display.setTextSize(1);
display.setTextColor(WHITE);
//display.clearDisplay();
//display.setCursor(0, 0);
//display.print("Menu Example");
//display.display();
//delay(1000);
}
void loop() {
int encoderValue = encoder.read();
if (encoderValue > 0 && menuIndex < maxMenuIndex) {
menuIndex++;
encoder.write(0);
} else if (encoderValue < 0 && menuIndex > 0) {
menuIndex--;
encoder.write(0);
}
if (menuIndex < scrollOffset) {
scrollOffset = menuIndex;
} else if (menuIndex >= scrollOffset + visibleItems) {
scrollOffset = menuIndex - visibleItems + 1;
}
if (menuIndex != lastMenuIndex) {
display.clearDisplay();
display.setCursor(0, 0);
for (int i = 0; i < visibleItems; i++) {
int menuItem = scrollOffset + i;
if (menuItem <= maxMenuIndex) {
display.print(menuItem + 1);
if (menuItem == menuIndex) {
display.print(". [");
} else {
display.print(". ");
}
display.print("Option ");
display.print(menuItem + 1);
if (menuItem == menuIndex) {
display.print("]");
}
display.println();
}
}
display.display();
lastMenuIndex = menuIndex;
}
// Check the switch state
if (digitalRead(switchPin) == LOW) {
delay(200); // debounce
executeSelectedOption();
}
delay(100);
}
void executeSelectedOption() {
display.clearDisplay();
display.setCursor(0, 0);
display.print("Selected: Option ");
display.println(menuIndex + 1);
switch (menuIndex) {
case 0:
display.print("Option 1 selected");
// Your code for Option 1
break;
case 1:
display.print("Option 2 selected");
// Your code for Option 2
break;
case 2:
display.print("Option 3 selected");
// Your code for Option 3
break;
case 3:
display.print("Option 4 selected");
// Your code for Option 4
break;
case 4:
display.print("Option 5 selected");
// Your code for Option 5
break;
case 5:
display.print("Option 6 selected");
// Your code for Option 6
break;
case 6:
display.print("Option 7 selected");
// Your code for Option 7
break;
}
display.display();
delay(100); // Display the result for 2 seconds before returning to the menu
}