BLYNK
BLYNK.IO       📲 GETTING STARTED       📗 DOCS       👉 SKETCH BUILDER

State not remembered outside of BLINK_WRITE function?

I’m just getting to grips with IoT from the excellent v0.1.
It might be a C thing (I’m no C coder, I just do assembly), but if I press a switch on the app, the BLINK_WRITE function associated with that virtual port (datastream) runs. I find I can copy the state (integer 0/1 in this case) into a variable and use that variable to immediately set an output pin state.
However, if I come back to use that variable in my 1 second event refresh loop, its state has been lost.
If I make a copy of its state within the BLYNK_WRITE function, that is remembered!
The sketch below says it all - if I copy both variables into new datastreams and look at them on the app, only the copy changes state.

#define BLYNK_TEMPLATE_ID ""
#define BLYNK_DEVICE_NAME ""
#define BLYNK_AUTH_TOKEN ""

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

char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "";
char pass[] = "";

int IRBoostOn = HIGH;    //D0  High = Relay 3 OFF
int IRBoostCopy = HIGH;

BlynkTimer timer;


BLYNK_WRITE(V0) //IRBoost Switch 
  {
    int IRBoostOn = param.asInt();
    digitalWrite(D0,IRBoostOn);
    IRBoostCopy = IRBoostOn; //because IRBoostOn state does not seem to carry over!!!                           
  }

void myTimerEvent()
{
     Blynk.virtualWrite(V1, IRBoostOn);
     Blynk.virtualWrite(V2, IRBoostCopy);
}

void setup()
{
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, myTimerEvent);
  pinMode(D0,OUTPUT);   //IR Boost
}

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



The int at the beginning of this line of code declares the IRBoostOn variable as local to the BLYNK_WRITE function.
The copy you are taking is to a global variable, so is visible everywhere.
Declare the IRBoostOn variable at the top of your sketch, making it global, and remove the int from the line of code to avoid re-declaring it locally.

This is C++ (OOP) code, not C.
If you search the interweb for “C++ variable scope” you’ll find more info.

Pete.

Ah. I had already declared it globally above, but my int in the function effectively declared a different variable?
Very many thanks for your help, as ever Pete.

Sorry, didn’t spot that when I was viewing your code on my phone.

Yes, one of the odd things about C++ is that it allows you to have local and global copies of the same variable. A bit of a mistake in the syntax definition of you ask me, but it is what it is.

Pete.