Using HCSR04 - Ultrasonic Sensor


How the Ultrasonic Sensor works:
Ultrasonic sensors work by emitting sound waves at a frequency too high for humans to hear. They then wait for the sound to be reflected back, calculating distance based on the time of the journey. This is similar to how radar measures the time it takes a radio wave to return after hitting an object.While some sensors use a separate sound emitter and receiver, it’s also possible to combine these into one package device, having an ultrasonic element alternate between emitting and receiving signals. This type of sensor can be manufactured in a smaller package than with separate elements, which is convenient for applications where size is at a premium.
Requirements:

Hardwares
  • Arduino Uno
  • HCSR04 Module
  • Jumper wires
  • LED series with 200 ohm resister(here we will use in-built led on 13 pin)
Softwares
Circuit Diagram

Code to be run:
//In this project, if a object appears in front of Ultrasonic Sensor with in the range 30-50 cm, the led will glow for 5 seconds.

#include <HCSR04.h>

HCSR04 hc(2,3);//initialisation class HCSR04 (trig pin , echo pin)
const int led= 13;
const int uplimit= 50, lowlimit= 30; //Any object between 30cm to 50cm to trigger led//

void setup()
  Serial.begin(9600); 
  pinMode(13,OUTPUT);
}

void loop()
  int distance = hc.dist();
  Serial.println(distance); 
  if( (distance>=lowlimit) && (distance<= uplimit))//OBJECT IN RANGE=LED ON FOR 5 SECS
  {
    digitalWrite(led, HIGH);
    delay(5000);
    digitalWrite(led, LOW);
  }
}


Code to Re-Connect Blynkserver Automatically

Issue: Sometimes the hardware(eg. Nodemcu) doesn't connect to router automatically, when there is a break in connection.




Solution: 
In this we'll add a timer. When there is no connection, the timer will start and try to reconnect in every specified time interval. to make this happen we need a library called as simple timer.
Extract this library to the library folder in Arduino folder in my documents.

Write the  following code:

#include <SimpleTimer.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

SimpleTimer timer;    //Creating simple timer variable 

char auth[] = "MxLDc********************KtUI";

char ssid[] = "**********";
char pass[] = "**********";

void setup()
{
  
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(10000, reconnectBlynk); //Setting interval to 10 seconds to Run function"reconnectBlynk"
}

void reconnectBlynk() {
  if (!Blynk.connected()) {
    if(Blynk.connect()) {
      BLYNK_LOG("Reconnected");
    } else {
      BLYNK_LOG("Not reconnected");
    }
  }
}
void loop()
{
  
  if (Blynk.connected()) {
    Blynk.run();
  }
  if (!Blynk.connected()) {
    timer.run();
  }
}