Ultrasonic and nodemcu wifi connection problem

Hi friends. I have a problem with my sketch. the nodemcu connection is not stable disconnect and reconnecting by itself. where is the problem

#define TRIGGER 4
#define ECHO    5

// NodeMCU Pin D2 > TRIGGER | Pin D1 > ECHO

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

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "79444998d67046ab93641e0a89c9fd67";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "MikroTik Home";
char pass[] = "mywifipass";
char server[] = "192.168.1.104";

void setup() {
  
  Serial.begin (9600);
  Blynk.begin(auth, ssid, pass, server);
  pinMode(TRIGGER, OUTPUT);
  pinMode(ECHO, INPUT);
  pinMode(BUILTIN_LED, OUTPUT);
}

void loop() {
  
  long duration, distance;
  digitalWrite(TRIGGER, LOW);  
  delayMicroseconds(2); 
  
  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10); 
  
  digitalWrite(TRIGGER, LOW);
  duration = pulseIn(ECHO, HIGH);
  distance = (duration/2) / 29.1;

   if (distance <= 150) {
    Blynk.virtualWrite(V0, 255);
}
  else {
    Blynk.virtualWrite(V0, 0);
  }

 if (distance <= 100) {
    Blynk.virtualWrite(V1, 255);
}
  else {
    Blynk.virtualWrite(V1, 0);
  }

   if (distance <= 80) {
    Blynk.virtualWrite(V2, 255);
}
  else {
    Blynk.virtualWrite(V2, 0);
  }

   if (distance <= 40) {
    Blynk.virtualWrite(V3, 255);
}
  else {
    Blynk.virtualWrite(V3, 0);
  }

   if (distance <= 20) {
    Blynk.virtualWrite(V4, 255);
}
  else {
    Blynk.virtualWrite(V4, 0);
  }

  
  
  Serial.print(distance);
  Serial.println("Centimeter:");
  Blynk.virtualWrite(V5, distance);
  delay(200);
  Blynk.run();
}

In the loop().

1 Like

:cry::cry::cry::cry: I cant see the problem can you guidance me ?

thanks

Perhaps you can start by saying what you think the purpose of a loop() is in an Arduino / ESP sketch?

1 Like

Hmmm. I think the problem in the delayMicroseconds ! maybe using simpletimer !?!

Yes you should look to use BlynkTimer to call any required functions at intervals. When you get experienced with Blynk you might be able to get away with delays in the loop but you are not at that level yet.

1 Like

also, take care to not put blynk virtual writes in conditions what are executed very often, it will cause flood error.

1 Like