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

digitalWrite() only works when switching between Virtual pin and Digital pin

Hey,

I have a strange problem. I use a Virtual pin V1 to manually control a relay which is on GPIO12 via a switch button. The problem is that GPIO12 is never switched when using digitalWrite(). I only get a LOW/HIGH when I switch in the Buttons Output Settings between V1 to D12 and back. I know this sounds crazy, but that’s the only way it works. And that works only until I restart the NodeMCU …

#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266_SSL.h>

BlynkTimer timer;

int RELAIS = 12;

void RELAIS_OPEN() {
  digitalWrite(RELAIS, LOW);
  Serial.println("Open");
  Blynk.virtualWrite(V1, 1);
}

void RELAIS_CLOSE() {
  digitalWrite(RELAIS, HIGH);
  Serial.println("Closed");
  Blynk.virtualWrite(V1, 0);
}

BLYNK_WRITE(V1) {
  int pinData = param.asInt(); 

  if (pinData == 1) {
    RELAIS_OPEN();
    int delayedOff = timer.setTimeout(3000, RELAIS_CLOSE); 
  }
}


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

void setup()
{
  Serial.begin(9600);

  Blynk.begin(auth, ssid, pass);
}

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

Any ideas?

Try changing this

int delayedOff = timer.setTimeout(3000, RELAIS_CLOSE);

to this

delayedOff = timer.setTimeout(3000, RELAIS_CLOSE);
1 Like

Unfortunately, that makes no difference. Even if I write it without the variable
timer.setTimeout(3000, RELAIS_CLOSE);

You need to add this to your setup() as well. Hopefully this does the trick.

pinMode(RELAIS, OUTPUT);           // set pin to output
digitalWrite(RELAIS, HIGH);       // set initial state of relay (CLOSED)

I believe at startup the pins default as INPUTs

1 Like

You have to follow these commands with a virtual sync command in order to actually process the new value.

http://docs.blynk.cc/#blynk-firmware-virtual-pins-control-blynksyncvirtualvpin

EDIT what you have is fine for just a display or changing a button state.

But if you want to “automatically” have the button "pressed’ after a state change, then the sync is needed.

1 Like

This works! Thank you so much!

1 Like

Yea, it was just a quick hack for showing the button state change. But thanks for your help :slight_smile:

can i use this code for Wemos D1 mini pro.

Which code, and what is it that you are trying to achieve?

Are you using Blynk Legacy or the new Blynk IoT?

Pete.