Cycle through Menu widget with physical button

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
BlynkTimer timer;

#define  buttonPin D2
int selectMode = 1;
int buttonPushCounter = 0; 
int buttonState = 0;       
int lastButtonState = 0; 

void setup() {
  pinMode(buttonPin, INPUT);
  timer.setInterval(100, mode);
  Blynk.begin("key", "SSID", "pass");
}

BLYNK_CONNECTED() {
  Blynk.syncVirtual(V1);
}

BLYNK_WRITE(V1) {
  selectMode = param.asInt();
}
void mode() {
  buttonState = digitalRead(buttonPin);
  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      buttonPushCounter++;
    } 
    delay(50);
  }
  lastButtonState = buttonState;
  if(buttonPushCounter % 4 == 1){
    selectMode=1;
  }else if(buttonPushCounter % 4 == 2){
    selectMode=2;
  }else if(buttonPushCounter % 4 == 3){
    selectMode=3;
  }else{
  selectMode=4;
  }
  
  switch (selectMode) {
  case 1: 
    //...
    break;
  case 2: 
    //...
    break;
  case 3: 
    //...
    break;
  default:
    //...
    break;
  }
}

void loop() {
  Blynk.run();
  timer.run();
}

Hello I have this code but its wrong.
I tried to write code that you are able to switch to the cases from the menu widget from Blynk app and also be able to cycle through the cases using a physical button in D2 pin

I’ve not tested this, but I’m guessing it wont be far off…

void mode()
{
  buttonState = digitalRead(buttonPin);
  if (buttonState != lastButtonState)
  {
    if (buttonState == HIGH)
    {
      selectMode++;
      if(selectMode>4) // Set this to the number of menu items
      {
         selectMode = 1;
      }
      Blynk.virtualWrite(V1,selectMode);
    } 
  }
  lastButtonState = buttonState;
}

Lets say that you have 4 menu items, and item 2 is currently selected. The selectMode variable will be equal to 2, thanks to your BLYNK_WRITE(V1) function, so pressing the button will add one to this then select item 3 in the menu with the virtaulWrite command.

When you get beyond the last (4th in this example) menu item you need to go back to item 1, hence this piece of code:

      if(selectMode>4) // Set this to the number of menu items
      {
         selectMode = 1;
      }

If this doesn’t give the results you’re expecting then try adding some serial print statements to monitor the variable values.

Pete.

1 Like

That worked perfectly!
I understand now, thank you sir.

1 Like

That was lucky then! :laughing:

Pete.