Turn on D5 HIGH for .5 seconds

I am using an ESP8266-12e for my project.
Blynk app is on iPhone 7 running newest iOS.
Blynk server
Blynk 0.6.1

Basically I want to connect to the internet with the ESP1 and press a button on the Blynk app to activate a latching relay. That relay turns OFF the ESP1 and ON another ESP8266-12e and sends some information to ThingSpeak, then after about 15 seconds uses its own pin5 to activate the reset side of the relay, turning OFF ESP2 and reactivating ESP1.

My big problem is that when I push the button on my Blynk app the D5 pin is slow to respond. Sometimes it reacts immediately and at other times it takes up to 4 seconds to react. So since I’m not sure how long it takes I hold down the button for 4 seconds. A second part of this is that when the button is released it does NOT turn off the D5 pin. So the pin remains active continuously.

When the ESP1 comes back on D5 is still active and activates the relay turning itself OFF and the ESP2 ON. A vicious cycle.

What I think I need to do is push the button for 4 seconds to make sure the ESP1 D5 pin is activated but detect when D5 goes to HIGH and then immediately make it go LOW and keep any further requests to make it go HIGH from coming in for 5 seconds to eliminate any hold over.
OR
I could somehow make D5 LOW every time the ESP1 is turned off and Blynk disconnects from the internet. I know it disconnects because on my app when the ESP1 is turned off I get a notification that Blynk is offline.

I don’t know if this would work because the button says its off but the D5 pin is still active.

Here is my code

I have people sign in and put their wifi and password and authorization code in and save it then it does that continuously after that.

For the part I am asking about I just designate the pin
pinMode(D5,OUTPUT);
make sure its OFF
digitalWrite (5,LOW);
and
Blynk.run();

I would really like someone help me get this going. If I have to rewire so ESP1 running Blynk doesn’t turn off that’s ok. Just so the button activates pin D5 for about .5 to 1 second to activates the latching relay I’ll be happy.

Thanks for any and everyones help


//NodeMCU 1.0 (ESP-12E Module constant connect)
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
//NEW AUTOCONNECT
#include <FS.h>         //https://github.com/esp8266/Arduino
#include <EEPROM.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>


//NEW AUTOCONNECT
const byte numChars = 32;
char receivedChars[numChars];

char Password[36]="";
char apiKey[32]="";
char apiKey2[32]="";
char channelKey[16]; 
char channelKey2[16];
String channelKey21= "&"; 
char auth[] = "";

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

 WiFiClient client;

//NEW AUTOCONNECT
char defaultHost[100] = "";  //Thing Speak IP address (sometime the web address causes issues with ESP's :/
const byte wifiResetPin = 13;
int interruptPinDebounce = 0;
long debouncing_time = 1000;
volatile unsigned long wifiResetLastMillis = 0;
bool shouldSaveConfig = false;
int address = 0;
byte value;
void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;}

  void handleWifiReset(){
    if(millis()<wifiResetLastMillis){
      wifiResetLastMillis = millis();
    }
    if((millis() - wifiResetLastMillis)>= debouncing_time){
      Serial.println("Clearing WiFi data resetting");
      WiFiManager wifiManager;
      wifiManager.resetSettings();
      SPIFFS.format();
      ESP.reset();
      delay(1000);
    }
    wifiResetLastMillis = millis();
  }
 
int addr = 0; 
//END NEW AUTOCONNECT

void setup() {
Serial.begin(115200);
pinMode(D5,OUTPUT);
//NEW AUTOCONNECT
  WiFiManager wifiManager;
    // put your setup code here, to run once:

pinMode(wifiResetPin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(wifiResetPin), handleWifiReset,FALLING);

 WiFiManagerParameter customAPIKey("apiKey", "Authorization Code", apiKey, 32);
 wifiManager.addParameter(&customAPIKey);
wifiManager.autoConnect("FloWT2");
    Serial.println("Connected");
  strcpy(apiKey, customAPIKey.getValue());

 
  if (shouldSaveConfig) {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["defaultHost"] = defaultHost;
    json["apiKey"] = apiKey;
    
    Serial.println("API");
    Serial.println("CHANNEL");
    Serial.print(apiKey);
    Serial.print(channelKey);
    String(apiKey2) = String(apiKey);
    
    
    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }
json.printTo(configFile);
    json.printTo(Serial);
    delay(1000);
    configFile.close();
    //end save
  }
  Serial.println("local ip");
  Serial.println(WiFi.localIP());

  strcpy(apiKey,customAPIKey.getValue());

 String( apiKey2) = String (apiKey);
  Serial.println("apiKEY");
  Serial.print(apiKey);
   EEPROM.begin(512);  //Initialize EEPROM
 
  
  EEPROM.write(addr, 'A');    //Write character A
  addr++;                      //Increment address
  EEPROM.write(addr, 'B');    //Write character A
  addr++;                      //Increment address
  EEPROM.write(addr, 'C');    //Write character A
   addr++;                      //Increment address
  EEPROM.write(addr, 'D');    //Write character A


 String www =  apiKey2;
 Serial.println("thisiswww");
  Serial.print (www);
  for(int i=0;i<www.length();i++) //loop upto string lenght www.length() returns length of string
  {
    EEPROM.write(0x0F+i,www[i]); //Write one by one with starting address of 0x0F
  }
  

  EEPROM.commit(); 

}
 

void loop() {
  digitalWrite(5,LOW);
  itt = 0;
  
  Serial.println("input");
  Serial.print(itt);
  
// digitalWrite(D1,HIGH);
  delay(1000);
 WiFiManager wifiManager;

WiFiClient client;

 
char defaultHost[100] = "api.thingspeak.com";



    EEPROM.begin(512);
    Serial.println("WHAT"); //Goto next line, as ESP sends some garbage when you reset it  
  Serial.print(char(EEPROM.read(addr)));    //Read from address 0x00
  addr++;                      //Increment address
  Serial.print(char(EEPROM.read(addr)));    //Read from address 0x01
  addr++;                      //Increment address
  Serial.println(char(EEPROM.read(addr)));    //Read from address 0x02
  addr++;                      //Increment address
  Serial.println(char(EEPROM.read(addr)));    //Read from address 0x03
   addr++;                      //Increment address
  Serial.println(char(EEPROM.read(addr)));    //Read from address 0x04

  //Read string from eeprom
  String www;   
  //Here we dont know how many bytes to read it is better practice to use some terminating character
  //Lets do it manually www.circuits4you.com  total length is 20 characters
  for(int i=0;i<32;i++) 
  {
    www = www + char(EEPROM.read(0x0F+i)); //Read one by one with starting address of 0x0F    
  } 

 Serial.println("this");
  Serial.print(www);  //Print the text on serial monitor

   www.toCharArray(auth,33);
Serial.println("auth");
Serial.print(auth);
   Blynk.begin(auth, ssid, pass); 


  delay(3000);
    
   Blynk.run();

 
 
}

Is the 3 second delay in the void loop causing your issues?

Is the 3 second delay in the void loop causing some of your issues?

That’s because you have a total of 4 seconds of blocking delay in your void loop.
You also have a massive amount of other stuff happening in your void loop, including multiple EEPROM reads. Each EEPROM memory location is usually good for around 100k read/write operations, so you’ll quickly kill your device.
Having Blynk.begin in your void loop is also a very bizarre thing to do.

Reading this might help:
http://help.blynk.cc/getting-started-library-auth-token-code-examples/blynk-basics/keep-your-void-loop-clean

I’m also intrigued by your desire to turn one device on from another and turn the first device off.
I’d guess that there is a much more elegant design solution to your problem, but it’s difficult to say without understanding more about your project.

Pete.

So removing the delays and moving the rest of the code into the setUp() worked to get the button to respond quickly. However my main goal still alludes me. I will come back and go into more detail later. Right now I need to get ready for guests. Hope everyone understands and stay healthy. Thanks.

So for a bit of an explanation. I have a remote sensor which communicates with the main hub (which is the part I am working on here) through RF, when certain conditions are met. It also communicates through wifi with ThingSpeak to record various other information and the fact that the the conditions are met and the RF signal has been sent.
The main hub receives the RF signal and through an addressed HT12D sends a pulse through a 2n2222 transistor, which activates the latching relay. Besides turning on one ESP and turning off another one the latching relay also connects to another component.
Why turn on one ESP and off another.Because I want to send a confirmation that the signal has been received and the connected component is operating. A failsafe if you will making sure the signal was received and to guard against false RF noise such as a garage door opener ext. If this happens and the component starts when not needed it is best to be aware of it and turn it off and to readdress the HT12E/Ds to avoid the problem in the future. Why turn off the other ESP that is connected to Blynk. No real reason except to save on energy.
Anyway I have all the component working properly except one small glitch.
The remote hub sends the RF and it is received and the ESP1 is turned off and the ESP2 is turned on and sends the information to ThingSpeak. After 15 seconds it reverses, turning on ESP1 and off ESP2 so no more messages are sent and Blynk is reengaged.
I also have a remote fob with a RF transmitter with addressable HT12E in it if one wants to turn on and off the connected component. And if I am away from home and I want to engaged the connected device for some reason I can by using the Blynk app button. Great.
The small glitch exists in that when I tap the Blynk button it makes the light on the ESP1 turn on, nothing else. If I wait about 15 seconds and tap the Blynk button again then the ESP1’s D5 sends a pulse through the transistor to the latching relay and the turn on/turn off happens and after 15 second everything is back to the basic state, ready to be activated by the remote hub, the remote fob or the Blynk app. I am going to repost my new code on the original post so anyone can look and see why this may be happening.
I tried to change my original post but wouldn’t let me.
Here is new code.

#define BLYNK_PRINT Serial

//NodeMCU 1.0 (ESP-12E Module constant connect)
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
//NEW AUTOCONNECT
#include <FS.h>         //https://github.com/esp8266/Arduino
#include <EEPROM.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>


//NEW AUTOCONNECT
const byte numChars = 32;
char receivedChars[numChars];

char Password[36]="";
char apiKey[32]="";
char apiKey2[32]="";
char channelKey[16]; 
char channelKey2[16];
String channelKey21= "&"; 
char auth[] = "";
byte pinState = LOW;
// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "";
char pass[] = "";   

 WiFiClient client;

//NEW AUTOCONNECT
char defaultHost[100] = "";  //Thing Speak IP address (sometime the web address causes issues with ESP's :/
const byte wifiResetPin = 13;
int interruptPinDebounce = 0;
long debouncing_time = 1000;
volatile unsigned long wifiResetLastMillis = 0;
bool shouldSaveConfig = false;
int address = 0;
byte value;
void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;}

  void handleWifiReset(){
    if(millis()<wifiResetLastMillis){
      wifiResetLastMillis = millis();
    }
    if((millis() - wifiResetLastMillis)>= debouncing_time){
      Serial.println("Clearing WiFi data resetting");
      WiFiManager wifiManager;
      wifiManager.resetSettings();
      SPIFFS.format();
      ESP.reset();
      delay(1000);
    }
    wifiResetLastMillis = millis();
  }
 
int addr = 0; 
//END NEW AUTOCONNECT

void setup() {
Serial.begin(115200);
pinMode(D5,OUTPUT);
//NEW AUTOCONNECT
  WiFiManager wifiManager;
    // put your setup code here, to run once:

pinMode(wifiResetPin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(wifiResetPin), handleWifiReset,FALLING);

 WiFiManagerParameter customAPIKey("apiKey", "Authorization Code", apiKey, 32);
 wifiManager.addParameter(&customAPIKey);
wifiManager.autoConnect("FloWT2");
    Serial.println("Connected");
  strcpy(apiKey, customAPIKey.getValue());

 
  if (shouldSaveConfig) {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["defaultHost"] = defaultHost;
    json["apiKey"] = apiKey;
    
    Serial.println("API");
    Serial.println("CHANNEL");
    Serial.print(apiKey);
    Serial.print(channelKey);
    String(apiKey2) = String(apiKey);
    
    
    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }
json.printTo(configFile);
    json.printTo(Serial);
    delay(1000);
    configFile.close();
    //end save
  }
  Serial.println("local ip");
  Serial.println(WiFi.localIP());

  strcpy(apiKey,customAPIKey.getValue());

 String( apiKey2) = String (apiKey);
  Serial.println("apiKEY");
  Serial.print(apiKey);
   EEPROM.begin(512);  //Initialize EEPROM
 
  
  EEPROM.write(addr, 'A');    //Write character A
  addr++;                      //Increment address
  EEPROM.write(addr, 'B');    //Write character A
  addr++;                      //Increment address
  EEPROM.write(addr, 'C');    //Write character A
   addr++;                      //Increment address
  EEPROM.write(addr, 'D');    //Write character A


 String www =  apiKey2;
 Serial.println("thisiswww");
  Serial.print (www);
  for(int i=0;i<www.length();i++) //loop upto string lenght www.length() returns length of string
  {
    EEPROM.write(0x0F+i,www[i]); //Write one by one with starting address of 0x0F
  }
  

  EEPROM.commit(); 


WiFiClient client;
 EEPROM.begin(512);
    Serial.println("WHAT"); //Goto next line, as ESP sends some garbage when you reset it  
  Serial.print(char(EEPROM.read(addr)));    //Read from address 0x00
  addr++;                      //Increment address
  Serial.print(char(EEPROM.read(addr)));    //Read from address 0x01
  addr++;                      //Increment address
  Serial.println(char(EEPROM.read(addr)));    //Read from address 0x02
  addr++;                      //Increment address
  Serial.println(char(EEPROM.read(addr)));    //Read from address 0x03
   addr++;                      //Increment address
  Serial.println(char(EEPROM.read(addr)));    //Read from address 0x04

  //Read string from eeprom
  String uuu;   
  
  for(int i=0;i<32;i++) 
  {
    uuu = uuu + char(EEPROM.read(0x0F+i)); //Read one by one with starting address of 0x0F    
  } 

 Serial.println("this");
  Serial.print(uuu);  //Print the text on serial monitor

   uuu.toCharArray(auth,33);
Serial.println("auth");
Serial.print(auth);
   Blynk.begin(auth, ssid, pass); 
}
 

void loop() {
  digitalWrite(5,LOW);
 
Blynk.run();
}```
Thanks

@gbenna please edit your latest post, using the pencil icon at the bottom, and delete your code that you’ve formatted using block quotes and ireplace it with code that has triple backticks at the beginning and end.
Triple backticks look like this:
```

You did this correctly in your first post, but not in your latest post.

I really don’t follow the logic of your need to keep turning your two devices on and off. There must be much more elegant ways of doing this.

Have you considered using MQTT messaging and Node-Red with the Blynk plug-in?
Adding off the shelf devices like the Sonoff 433MHz Gateway re-flashed with Tasmota makes RF Comms very easy, and this would send MQTT messages to the broker. Using this approach it is simple to have commands and confirmation messages configured, along with telemetry and heartbeat data as required.

Node_Red can also integrate with services like Thingspeak very easily, as well as other services like Amazon Alexa etc.

This approach is the heart of my home automation system and creates a very reliable and versatile configuration which is extremely scalable.

Pete.

I will look into this thanks. Can you think of any reason why I need to tap the button twice though to get the esp to activate the D5 pin? Oh, I solved the earlier problem by adding a 1N4148 to the power source of the ESP8266-12e.