I want to initiate BLYNK_WRITE(V0) on void hcsr04

Hello Everybody,
I need your help on my project.
I want to call BLYNK_WRITE(V0) on next void hcsr04 (). it gives an error.

#define BLYNK_FIRMWARE_VERSION        "0.1.0"

#define BLYNK_PRINT Serial

//#define BLYNK_DEBUG

#define APP_DEBUG

// Uncomment your board, or configure a custom board in Settings.h

//#define USE_WROVER_BOARD

#include "BlynkEdgent.h"

#include <ESP32Servo.h>

#include <HCSR04.h>

const byte triggerPin = 13;
const byte echoPin = 12;
UltraSonicDistanceSensor distanceSensor(triggerPin, echoPin); 

Servo servo;

int led1=19;
int led2=22;
int led3=23;
int myServo=5;
float distance;
int pinValue;

BLYNK_WRITE(V0) {

  int pinValue = param.asInt();

  digitalWrite(led1,pinValue);

  if (pinValue == 1) {

    Serial.println("DEVICE ON");

   

  }

  else {

Serial.println("DEVICE OFF");

  }

}

void hcsr04() {

  float distance = distanceSensor.measureDistanceCm();

  Serial.println(distance);

  Blynk.virtualWrite(V2, distance);

   int pinValue=BLYNK_WRITE(V0); //START IF DEVICE is ON, GET VALUE FROM V0 

  if (pinValue == 1) {

  Serial.println("ON");

  if (distance<200) {

    digitalWrite(led2, HIGH);

    digitalWrite(led3, LOW);

  }

  else {

      digitalWrite(led3, HIGH);

      digitalWrite(led2, LOW);

}

}

  else {

 Serial.println("OFF");

}

}

void setup()

{

  Serial.begin(115200);

  delay(100);

  pinMode(led1, OUTPUT);

  pinMode(led2, OUTPUT);

  pinMode(led3, OUTPUT);

  servo.attach(myServo); 

  BlynkEdgent.begin();

  timer.setInterval(500L,hs04);

}

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

@hasanuz2001 please edit your post, using the pencil icon at the bottom, and add triple backticks at the beginning and end of your code so that it displays correctly.
Triple backticks look like this:
```

Pete.

Sorry PeteKnight, and thank you

As you’ve discovered, you cant do this.
BLYNK_WRITE(vPin) is a special callback function which is triggered automatically when the value of the virtual; pin changes on the server.

What you should do is to save the value of the virtual pin top a GLOBAL variable, s that it’s available elsewhere within your sketch.

You’ve already declared a global variable called pinValue at the top of your sketch…

However, you then re-declare this as a local variable in your BLYNK_WRITE(V0) callback function…

Changing this to…

BLYNK_WRITE(V0) {

  pinValue = param.asInt();

would make the pinValue value available globally.

You should also add the following code somewhere in your sketch…

BLYNK_CONNECTED()
{
  Blynk.syncVirtual(V0);
}

This will force the server to send the latest V0 value when the device connects or re-connects to the Blynk server, causing the BLYNK_WRITE(V0) callback to trigger and the latest value to be stored in the pinValue variable.

Pete.

Thank you Pete. Now It is working correctly )) I am very happy.

1 Like