How to loop virtual pin

Hello Community!
I need your help.
I have very long code for vitual pins. Is it possible to make loop for identtical codes in order to shorten codes.

BLYNK_WRITE(V0) {
  btn1 = param.asInt();
  if (btn1 == 1) {
    knum = 0;
    pushed[knum] = 1;
    controlRelay(knum);
  }
  else {
    knum = 0;
    pushed[knum] = 0;
    controlRelay(knum);
  }
}
BLYNK_WRITE(V1) {
  btn1 = param.asInt();
  if (btn1 == 1) {
    knum = 1;
    pushed[knum] = 1;
    controlRelay(knum);
  }
  else {
    knum = 1;
    pushed[knum] = 0;
    controlRelay(knum);
  }
}
BLYNK_WRITE(V2) {
  btn1 = param.asInt();
  if (btn1 == 1) {
    knum = 2;
    pushed[knum] = 1;
    controlRelay(knum);
  }
  else {
    knum = 2;
    pushed[knum] = 0;
    controlRelay(knum);
  }
}
BLYNK_WRITE(V3) {
  btn1 = param.asInt();
  if (btn1 == 1) {
    knum = 3;
    pushed[knum] = 1;
    controlRelay(knum);
  }
  else {
    knum = 3;
    pushed[knum] = 0;
    controlRelay(knum);
  }
}

for example I need to make loop like this.

int V[]={0,1,2,3,4,5,6,7,8,9};
for (int i = 0; i < 9; i++)
    {
      BLYNK_WRITE(V[i]) {
  btn1 = param.asInt();
  if (btn1 == 1) {
    knum = i;
    pushed[knum] = 1;
    controlRelay(knum);
  }
  else {
    knum = i;
    pushed[knum] = 0;
    controlRelay(knum);
  }
}
    }

but last code is not working.

You should use the BLYNK_WRITE_DEFAULT() function. This only works if you don’t already have a BLYNK_WRITE(vPin) function for the virtual pins you’re using, so you’ll need to comment-out your existing BLYNK_WRITEs when testing.

This is how it works…

BLYNK_WRITE_DEFAULT()
{
  int widget_pin = request.pin;      // Which virtual pin triggered this BLYNK_WRITE_DEFAULT callback?
  int widget_value = param.asInt();  // Get the value from the virtual pin (0 = off, 1 = on)

// Your code in here to do the rest...

}

Pete.

2 Likes

Thank you Pete, Now my code is short and very understandable.

1 Like