One button active others deactivated nodemcu esp8266

Hi This is my first post. I have searched at some length for a solution. My project is used to control two relays which controls two water pumps. Unfortunately if not careful both pumps can be active at the same time.
My problem is to not have both buttons active at once
The solution would be to deactivate the other button when one is active.

V0-Display
V1-Display
V3-Button(clear)
V4-Button(pump)
V5-Menu
V6-RTC
V7-LCD
V10-Table
*/
//#define BLYNK_DEBUG           // Comment this out to disable debug and save space
#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <ESP8266WebServer.h>
//#include <SimpleTimer.h>
#include <TimeLib.h>
#include <WidgetRTC.h>
#include <Ticker.h>              //for LED status
Ticker ticker;

char auth[] = "";
// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] ="";
char pass[] ="";

SimpleTimer timer;
WidgetRTC rtc;         
//BLYNK_ATTACH_WIDGET(rtc, V6)
WidgetTerminal terminal(V2);
WidgetLCD lcd(V7);
bool simulation = false;     

byte sensorInterrupt = 4;   // WeMos & NodeMCU D2
byte sensorPin       = 4;   // WeMos & NodeMCU D2
byte pumpInterrupt   = 5; //2;  //5;   // WeMos D1 ModeMCU D3
byte pumpPin         = 5; //2;  //5;   // WeMos D1 ModeMCU D3

// The hall-effect flow sensor outputs approximately 4.5 pulses per second per litre/minute of flow.
float calibrationFactor = 4.5;
volatile byte pulseCount;  
float flowRate;
unsigned int flowMilliLitres;
unsigned long totalMilliLitres;
unsigned long oldTime;

#define averageperiod 5         // currently set to average the flow every 5 seconds
int countseconds = 0;           // count up to averageperiod
int averageflow = 0;            // used for averaging flow over averageperiod
bool notificationsent = false;  // to ensure just one message for each flow start
bool pumpState = false;         // pump is OFF on start up
bool masterState = false;       // 
bool flowoffprintonce = false;  // to ensure just one serial and terminal print for each flow stop
int rowIndex = 0;                //Saurabh
String currentDate  ;
String daybefore;
int rtctimer = 1; //check if RTC is OK and then disable / delete this #1 timer
int currentDatesi = 0;         //Saurabh simulation
int daybeforesi=currentDatesi;
int menu=0;
int s;


void setup()
{

  Serial.begin(115200);
  Serial.println();
 pinMode(sensorPin, INPUT);
 digitalWrite(sensorPin, HIGH);
  pinMode(pumpPin, OUTPUT);
  digitalWrite(pumpPin, LOW);  // ACTIVE HIGH, pump relay set to OFF on restart
  
  flowMilliLitres   = 0;
  totalMilliLitres  = 0;
  oldTime           = 0;
  flowRate          = 0.0;
  if(simulation == true){
    pulseCount        = 47;
  }
  else{
    pulseCount        = 0;
  }

  // Configured to trigger on a FALLING state change (transition from HIGH state to LOW state)
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING);//FALLING

  // Configured to trigger on a CHANGE state change LOW to HIGH or HIGH to LOW
    attachInterrupt(pumpInterrupt, pumpToggle, CHANGE);
  Blynk.begin(auth, ssid, pass);
  rtc.begin();
  terminal.println("Connected to Blynk");
  terminal.println(WiFi.localIP());
  terminal.flush(); 
  timer.setInterval(1000L, showFlow);
  timer.setInterval(100L, pumpControl);  // check if pump needs to be switched ON or OFF every 0.1s
  rtctimer = timer.setInterval(2000L, checkRTC);   // check every 2s if RTC is correct
}
BLYNK_CONNECTED() {
Blynk.syncVirtual(V5);
Blynk.syncVirtual(V4);
}
void showFlow()  // average the flow over averageperiod
{  
    detachInterrupt(sensorInterrupt);  // Disable the interrupt while calculating flow rate and sending the value to the host        
    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;
    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.
    oldTime = millis();
    
    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.
    flowMilliLitres = (flowRate / 60) * 1000;
    
    // Add the ml passed in this second to the cumulative total
    totalMilliLitres += flowMilliLitres;
    
    // Print the flow rate for this second in litres / minute
    Serial.print("Flow rate: ");
    Serial.print(int(flowRate));  // Print the integer part of the variable
    Serial.print("L/min");
    Serial.print("\t");          // Print tab space
    // Print the cumulative total of litres flowed since starting
    Serial.print("Output Liquid Quantity: ");        
    Serial.print(totalMilliLitres);
    Serial.print("mL"); 
    Serial.print("\t");       // Print tab space
    Serial.print(totalMilliLitres/1000);
    Serial.println("L");
    if(simulation != true){  
      pulseCount = 0; // Reset the pulse counter so we can start incrementing again
    }
    countseconds++;
    if(countseconds > 0){    // used to skip the first rogue data flow reading
      averageflow = averageflow + flowRate;   // used to calculate the average flow over averageperiod cycles
    }
    if(countseconds == averageperiod){
      Serial.print("Average water flow in litres / M is ");
      Serial.println(averageflow / averageperiod);
      Blynk.virtualWrite(V0, int(averageflow) / averageperiod);
      Blynk.virtualWrite(V1, totalMilliLitres/1000);
      countseconds = 0;  // reset the counter
      chkFlow();           
      averageflow = 0;     // reset the average but only after chkFlow() function
    }
       attachInterrupt(sensorInterrupt, pulseCounter, FALLING);  // Enable the interrupt again now that we've finished sending output
}

void chkFlow(){
  if((averageflow > 3) && (notificationsent == false)){  // guess of a decent water pressure
    Serial.println("Water IS flowing.");
    lcd.clear();
    lcd.print(0,0,"Water is flowing");
    Blynk.email("Water Flow Sensor", "Water IS flowing.");
    Blynk.notify("Sensor: Water IS flowing.");
    notificationsent = true;         // stop getting messages until water stops flowing and starts again
    flowoffprintonce = false;        // when water stops flowing again we can restart serial and terminal print (once)
    
  }
  if((averageflow <= 3)&& (flowoffprintonce == false)){
    Serial.println("Water is NOT flowing.");
    lcd.clear();
    lcd.print(1,0,"Water is NOT");
    lcd.print(4,1,"flowing");
    notificationsent = false;  // when water starts flowing again we can send another notification
    flowoffprintonce = true;      // stop serial and terminal prints after first pass of water stopping
    s=0;
  }
 if(averageflow <= 3){
     digitalWrite(pumpPin, LOW);   // turn off pump //s*
   }
if(averageflow>3 && menu == 1){
    digitalWrite(pumpPin, HIGH);   // turn on pump //s*
    Blynk.virtualWrite(V8, "ON");
    Blynk.virtualWrite(V4, 1);     // update app button on V4  COSTAS//s*
   }

}
void pulseCounter()
{
  pulseCount++;  // Increment the pulse counter
}

void pumpToggle(){                // toggle just pumpState OFF and ON from pin interrupt
  pumpState = !pumpState;         // don't do anything else in this function or the system will crash
  //Serial.println(pumpState);      // for debugging only  TODO comment this out later     
}

void pumpControl()                // toggle pump OFF and ON
{
  detachInterrupt(pumpInterrupt);  // disable interrupt
  if(pumpState == masterState){
    // do nothing
  }
  else{  
    masterState = pumpState;
    if(pumpState == true){
    Blynk.virtualWrite(V4, 1);
    Blynk.virtualWrite(V8, "ON");
    // Blynk.setProperty(V8, "color","#48E06B");
    Serial.println("Pump turned ON"); 
    }
    else{
      Blynk.virtualWrite(V4, 0);
      Blynk.virtualWrite(V8, "OFF");
   //   Blynk.setProperty(V8, "color","#04C0F8");
      Serial.println("Pump turned OFF"); 
    }
  }
  terminal.flush();

  attachInterrupt(pumpInterrupt, pumpToggle, CHANGE);   // enable pump pin interrupt
}
void checkRTC(){
  if(year() != 1970){
    timer.disable(rtctimer);  // disable rtctimer now RTC is ok
    //rtcupdated = true; // can be commented out as checkRTC will stop when RTC is ok
    currentDate = String(day()) + "/" + month() + "/" + year();   // etc
    terminal.println("RTC started");
    daybefore=currentDate;
    timer.setInterval(60000L, table);   //start table() now RTC is OK
  }
}
void table()                               //Saurabh
{
  currentDate = String(day()) + "/" + month() + "/" + year();  // etc
   if(currentDate != daybefore)
    {
    //currentDate = String(day()) + "/" + month() + "/" + year();
    Blynk.virtualWrite(V10, "add", rowIndex,daybefore,totalMilliLitres/1000+String(" litre")); //Saurabh
    Blynk.virtualWrite(V1, 0);
    Serial.println("working");
    flowMilliLitres = 0;
    totalMilliLitres = 0;
    daybefore=currentDate; 
    }
}
BLYNK_WRITE(V3){   // reset with button in PUSH mode on virtual pin 3
  int resetdata = param.asInt();
  if(resetdata == 1){
    Serial.println("Clearing data");
    Blynk.virtualWrite(V0, 0);
    Blynk.virtualWrite(V1, 0);
    averageflow = 0;
    countseconds = 0;
    flowMilliLitres = 0;
    totalMilliLitres = 0;
  }
}
BLYNK_WRITE(V20){   // reset with button in PUSH mode on virtual pin 20
  int resetdata = param.asInt();
  if(resetdata == 1){
    Serial.println("Clearing table data");
    Blynk.virtualWrite(V10, "clr");
   
  }
}
BLYNK_WRITE(V4){   // Button in SWITCH mode on virtual pin 4 to control relay
  int controlRelay = param.asInt();
  if(controlRelay == 1){
    digitalWrite(pumpPin, HIGH);  // turn relay ON
   // Blynk.virtualWrite(V8, "ON"); 
  }
  else{
    digitalWrite(pumpPin, LOW);  // turn relay OFF 
     //Blynk.virtualWrite(V8, "OFF"); 
  }
  pumpControl();
}
BLYNK_WRITE(V5)
{
 switch(param.asInt()){
  case 1:{
     lcd.clear();
    lcd.print(1,0,"Automatic Mode");
    lcd.print(5,1,"Selected");
    menu=1;
    break;
  }
  case 2:{
    lcd.clear();
    lcd.print(3,0,"Manual Mode");
    lcd.print(5,1,"Selected");
    menu=0;
    break;
  }
 }
}
void loop(){
  Blynk.run();
  timer.run();
}```

@Dave_Dunphy please edit your post, using the pencil icon at the bottom, and add triple backticks at the beginning and end of your code so that it displays correctly.
Triple backticks look like this:
```

Pete.

Thank you

Are you using the free plan or the plus plan ?

what’s the difference?

Both will work but There’s a widgets in the plus plan that will make things easier, instead of using 2 buttons.
I’m using a segmented switch and step h to control 2 motors using relays.

Currently free plan. Still in development mode.

Have you tried to use automation ?

My scope of Blynk is limited so no. The original code was provided to me.

automation will save your day, go and try it and I will guide you if you need any help.

This is a Legacy sketch, no Template ID and no forced connection to blynk.cloud.

Automations won’t work.

Pete.

Yes, I noticed.

@Dave_Dunphy are you using blynk iot or blynk legacy ?

Blynk iot

So as pete just mentioned, this code is not gonna work, you have to modify it.
Read this :
https://docs.blynk.io/en/blynk-1.0-and-2.0-comparison/migrate-from-1.0-to-2.0

/*************************************************************

  This example shows how to synchronize Button widget
  and physical button state.

  App project setup:
    Button widget attached to V2 (Switch mode)
 *************************************************************/

// Template ID, Device Name and Auth Token are provided by the Blynk.Cloud
// See the Device Info tab, or Template settings
#define BLYNK_TEMPLATE_ID           "TMPLxxxxxx"
#define BLYNK_DEVICE_NAME           "Device"
#define BLYNK_AUTH_TOKEN            "YourAuthToken"


// Comment this out to disable prints and save space
#define BLYNK_PRINT Serial


#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

char auth[] = BLYNK_AUTH_TOKEN;

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "YourNetworkName";
char pass[] = "YourPassword";

// Set your LED and physical button pins here
const int ledPin = 7;
const int btnPin = 8;

BlynkTimer timer;
void checkPhysicalButton();

int ledState = LOW;
int btnState = HIGH;

// Every time we connect to the cloud...
BLYNK_CONNECTED() {
  // Request the latest state from the server
  Blynk.syncVirtual(V2);

  // Alternatively, you could override server state using:
  //Blynk.virtualWrite(V2, ledState);
}

// When App button is pushed - switch the state
BLYNK_WRITE(V2) {
  ledState = param.asInt();
  digitalWrite(ledPin, ledState);
}

void checkPhysicalButton()
{
  if (digitalRead(btnPin) == LOW) {
    // btnState is used to avoid sequential toggles
    if (btnState != LOW) {

      // Toggle LED state
      ledState = !ledState;
      digitalWrite(ledPin, ledState);

      // Update Button Widget
      Blynk.virtualWrite(V2, ledState);
    }
    btnState = LOW;
  } else {
    btnState = HIGH;
  }
}

void setup()
{
  // Debug console
  Serial.begin(115200);

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk.cloud", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);

  pinMode(ledPin, OUTPUT);
  pinMode(btnPin, INPUT_PULLUP);
  digitalWrite(ledPin, ledState);

  // Setup a function to be called every 100 ms
  timer.setInterval(100L, checkPhysicalButton);
}

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

You can use this sketch to test, with this sketch you will control a relay using the app and a push button.

Thanks John
Blynk iot is new and I’m actually using legacy(old version), Would it be wise to start a new with iot? I used the device alot.

I recommend you to start using blynk iot because blynk legacy will be retired some day.

Install blynk iot app and sign in and I will be here to help you, if you need any help just feel free to ask.

I have installed both pc and Android. Now the learning curve. As I mentioned the original code was provided to me. Would it be hard to use the code from legacy? I’m and good systems and mechanical guy, but seriously lack in coding. Would you be interested in converting this code?