Inconsistent pin states in app and hardware

Hi,

In my project, I want to have a value that has a default value set in code, but is configurable. To do this, I’ve added a numeric input widget in Blynk app and attached it to V1.

int value = 220;

BLYNK_CONNECTED() {
  // call BLYNK_WRITE on all pins
  Blynk.syncAll();
  // if BLYNK_WRITE was called, value = value set in app
  // if BLYNK_WRITE was not called, value = 220
  Blynk.virtualWrite(V1, value);
}

BLYNK_WRITE(V1) {
  // read value set in app
  // if app hasn't been opened yet, this won't be called
  value = param.asInt();
}

BLYNK_READ(V1) {
  // if app requests value, send it
  Blynk.virtualWrite(V1, value);
}

When the app is launched for the first time, the hardware continues to use the default value set in code 220. The app also shows the default value of 220 in the numeric input widget. If I change the value in the widget to, say 100, the hardware correctly calls BLYNK_WRITE and gets the value set in the app. So far so good.

When the hardware is power-cycled, the hardware correctly reads 100 from Blynk and works fine. However, the app behaves erratically. Sometimes, it shows 100 (correct). But sometimes, it shows 220 (incorrect).

If I add a value display widget, attached to the same pin and polling at regular intervals, then when the device power-cycles, both widgets show either 220 or 100 during the first poll but correctly show 100 subsequently.

Am I trying to do this the wrong way? Or is this a limitation of the library? I don’t want to use two widgets for this. I want to just use the numeric-input widget. Can it be done?

Thanks and best regards,
Asim

Try removing Blynk.virtualWrite(V1, value) inside BLYNK_CONNECTED

int value = 220;

BLYNK_CONNECTED() {
  Blynk.syncAll();
}

BLYNK_WRITE(V1) {
  value = param.asInt();
}

Hi Eugene,

If I remove Blynk.virtualWrite(V1, value) inside BLYNK_CONNECTED then the default value of value = 220 does not get pushed to the app when first run. The app shows value = 0 while the hardware uses value = 220. When I set any value from the app, then both the app and hardware use the newly-set value.

If the widget has not been initialized yet, I want it to show the default value stored in hardware, instead of 0.

Asim

Oh, right. Then yes, use BLYNK_APP_CONNECTED:

int value = 220;

BLYNK_CONNECTED() {
  Blynk.syncAll();
}

BLYNK_APP_CONNECTED() {
  Blynk.virtualWrite(V1, value);
}

BLYNK_WRITE(V1) {
  value = param.asInt();
}

Make sure you have Notify devices when app connected enabled in project settings

1 Like

Hi Eugene,

I think this should work! =) Give me an hour or so to test it and report back. Thanks for the idea. =)

Best regards,
Asim

Hi again Eugene,

I can confirm this works as expected. =) Thanks a ton!

Asim