Gedaan en nog een bug opgelost, Was vergeten om select aan te passen.
Nieuwste werkende code :
#include <LiquidCrystal.h>
#define ISPRESSED LOW
#define NUMELEMENTS(x) (sizeof(x) / sizeof(x[0]))
uint8_t buttonState = !ISPRESSED;
uint8_t choice = 1;
uint8_t selectedChoice = 0 ;
// function prototypes for button functions
void buttonUp();
void selectChoice();
void buttonDown();
struct Button {
const uint8_t pin;
unsigned long lastDebounceTime;
uint8_t lastButtonState;
uint8_t currDebouncedState;
uint8_t prevDebouncedState;
void (*func)();
};
unsigned long long debounceDelay = 20;
// Create and initialize an array of 3 Button objects
Button buttonList[] = {
{ A3, 0, !ISPRESSED, !ISPRESSED, !ISPRESSED, buttonUp }, // buttomUp
{ A2, 0, !ISPRESSED, !ISPRESSED, !ISPRESSED ,selectChoice}, // select
{ A1, 0, !ISPRESSED, !ISPRESSED, !ISPRESSED, buttonDown }, // buttondown
};
char buffer[128];
const char *menuItems[] = {
"Sweep",
"Staart",
"Twee keer",
};
LiquidCrystal LCD(12, 11, 10, 9, 8, 7); //Create Liquid Crystal Object called LCD
void showMenu(int counter) {
LCD.clear();
LCD.setCursor(0, 0);
LCD.print("--->");
LCD.setCursor(5, 0);
LCD.print(menuItems[counter % NUMELEMENTS(menuItems)]);
LCD.setCursor(5, 1);
LCD.print(menuItems[(counter + 1) % NUMELEMENTS(menuItems)]);
};
void setup() {
LCD.begin(16, 2);
for (uint8_t cnt = 0; cnt < NUMELEMENTS(buttonList); cnt++) {
pinMode(buttonList[cnt].pin, INPUT_PULLUP);
}
Serial.begin(9600);
showMenu(choice);
}
void buttonUp()
{
if (choice > 0) {
choice--;
} else {
choice = 2;
}
}
void selectChoice()
{
selectedChoice = choice % NUMELEMENTS(menuItems) ;
Serial.print("U hebt gekozen voor ");
Serial.println(menuItems[selectedChoice]);
}
void buttonDown()
{
++choice;
Serial.print("Waarde counter : ");
Serial.println(choice);
}
void readButton(int index) {
buttonState = digitalRead(buttonList[index].pin);
if (buttonState != buttonList[index].lastButtonState) {
buttonList[index].lastDebounceTime = millis();
}
if ((millis() - buttonList[index].lastDebounceTime) > debounceDelay) {
buttonList[index].currDebouncedState = buttonState;
}
if (buttonState != buttonList[index].lastButtonState) {
buttonList[index].lastButtonState = buttonState;
}
}
void loop()
{
for (uint8_t cnt = 0; cnt < NUMELEMENTS(buttonList); cnt++)
{
readButton(cnt);
if (buttonList[cnt].currDebouncedState != buttonList[cnt].prevDebouncedState)
{
buttonList[cnt].prevDebouncedState = buttonList[cnt].currDebouncedState;
// bug fgix
if (buttonList[cnt].currDebouncedState == ISPRESSED)
{
if (buttonList[cnt].func != nullptr) {
buttonList[cnt].func();
showMenu(choice);
}
}
else
{
}
}
}
}
Misschien een idee om van het aantal elementen in het menu ook een variable te maken.
Ik zie nog op meerdere plaatsen NUMELEMENTS(menuItems) staan