HC-SR04 – Blog eTechPath https://blog.etechpath.com Tue, 03 Jan 2023 12:40:09 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.3 https://blog.etechpath.com/wp-content/uploads/2017/08/BrandLogo12-150x150.png HC-SR04 – Blog eTechPath https://blog.etechpath.com 32 32 Water Tank Level Automation using ESP8266 and HC-SR04 Ultrasonic Sensor. https://blog.etechpath.com/water-tank-level-automation-using-esp8266-and-hc-sr04-ultrasonic-sensor/ https://blog.etechpath.com/water-tank-level-automation-using-esp8266-and-hc-sr04-ultrasonic-sensor/#respond Tue, 18 Oct 2022 09:47:57 +0000 https://blog.etechpath.com/?p=976

About:

In this tutorial, we will learn how to interface hc-sr04 ultrasonic sensor with ESP8266 module and display the water tank level on mobile browser.

Table of Contents:

  • HC-SR04 Module
  • How Ultrasonic sensor works
  • Interfacing sensor module with NodeMCU
  • Programming NodeMCU with ArduinoIDE

HC-SR04 Module and How it works

HC-SR04 is an Ultrasonic sensor module which includes ultrasonic transmitter, receiver and control circuit in single compact PCB.  HC-SR04 has distance measurement ability ranging from 2cm to 400cm. These small units are very accurate, and its accuracy can be reach up to 3mm.

Ultrasonic modules work on the principle similar to radar or sonar- sensors. It generates high frequency signals from the transmitter of about 40kHz towards the sensing object and receives echo signal back to the receiver. Then we can calculate object distance using time interval between the sending of signal and the receiving of echo pulse.

Circuit Diagram:

Libraries:

Code:

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <Hash.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <HCSR04.h>

const char* ssid     = "WaterLevel"; //Access point ssid
const char* password = "12341234";   //Access point password

float l = 0.0;
float per = 0.0;
float fcm = 0;
//Rectangular Tank dimentions in cm
float lcm = 200;  //Length
float bcm = 200;    // width
float hcm = 130;  // Height, from Sensor to tank bottom

HCSR04 ultrasonicSensor(D6, D5, 20, 300);
AsyncWebServer server(80);
unsigned long previousMillis = 0;
const long interval = 1000;  

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    html {
     font-family: Arial;
     display: inline-block;
     margin: 0px auto;
     text-align: center;
    }
    h2 { font-size: 3.0rem; Color:DodgerBlue; }
    h3 { font-size: 1.5rem; Color:Tomato; }
    p { font-size: 3.0rem; }
    .units { font-size: 1.2rem; }
    .temp-labels{
      font-size: 1.5rem;
      vertical-align:middle;
      padding-bottom: 10px;
    }
  </style>
</head>
<body>
  <h2>Water Tank Level</h2>
  <h3>www.eTechPath.com</h3>
  <p>
    <span id="permap">%PERMAP%</span>
    <sup class="units">%</sup> 
  </p>
   <p>
   <span id="liter">%LITER%</span>
    <sup class="units">Liters</sup>
  </p>
      <p>
    <span id="distance">%DISTANCE%</span>
    <sup class="units">Cm</sup>
  </p>
</body>
<script>
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("permap").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/permap", true);
  xhttp.send();
}, 1000 ) ;
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("liter").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/liter", true);
  xhttp.send();
}, 1000 ) ;
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("distance").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/distance", true);
  xhttp.send();
}, 1000 ) ;
</script>
</html>)rawliteral";

// Replaces placeholders with sensor values
String processor(const String& var){
 
  if(var == "DISTANCE"){
    return String(fcm);
  }
  else if(var == "LITER"){
    return String(l);
  }
  else if(var == "PERMAP"){
    return String(per);
  }
  return String();
}
void setup(){
  Serial.begin(115200);  
  ultrasonicSensor.begin(); 
  Serial.print("Setting AP (Access Point)…");
  WiFi.softAP(ssid, password);

  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);
  Serial.println(WiFi.localIP());

  // Route for root
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", index_html, processor);
  });
  server.on("/permap", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", String(per).c_str());
  });
  server.on("/liter", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", String(l).c_str());
  });
  server.on("/distance", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", String(fcm).c_str());
  });
  server.begin();
} 
void loop()
{  
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) 
  {
    previousMillis = currentMillis;
     float newdistance = ultrasonicSensor.getMedianFilterDistance(); //pass 3 measurements through median filter, better result on moving obstacles
    if (newdistance != HCSR04_OUT_OF_RANGE)
    {
      Serial.print("sensor raw value:");
      Serial.println(newdistance);
      fcm = hcm - newdistance;
      float v = fcm * lcm * bcm ;
      l = v / 1000;
      per = map(fcm, 0, hcm, 0, 100);
      Serial.println(per);
      Serial.println(l);
      Serial.println(fcm);     
    }
    else 
    {
      Serial.println(F("out of range"));
    }     
  }
}

Video:

]]>
https://blog.etechpath.com/water-tank-level-automation-using-esp8266-and-hc-sr04-ultrasonic-sensor/feed/ 0
Digital distance measuring device using ultrasonic sensor SR04, OLED display and Arduino https://blog.etechpath.com/digital-distance-measuring-device-using-ultrasonic-sensor-sr04-oled-display-and-arduino/ https://blog.etechpath.com/digital-distance-measuring-device-using-ultrasonic-sensor-sr04-oled-display-and-arduino/#respond Sat, 05 May 2018 14:48:07 +0000 https://blog.etechpath.com/?p=573 About:

In this project i will explain how to interface SR04 ultrasonic sensor module with Arduino and display result on OLED display.




Components:

Arduino

SR04 Ultrasonic sensor module

OLED display i2c

Wires and basic tools




Circuit Diagram:

Description: 

  1. Connect SR04 ultrasonic sensor power to arduino +5v and GND also connect Trigger and Echo pin to arduino pin 9 and pin 8 as shown in above circuit diagram.
  2. In same way connect OLED power to arduino and connect SCL & SDA of oled display to arduino pin A5 and pin A4.
  3. Download arduino code and all libraries form download section, compile the code and upload it to your arduino.
  4. If you are new to ultrasonic sensors, do visit this post for basic study “SR04 Ultrasonic Sensor Module Basics”





Code:

/******************************************************************
 * Project: Printing utrasonic sensor data on OLED display
 * Author: Pranay Sawarkar
 * Website: www.etechpath.com
 *
 * This example is for a 128x32 pixel monocrome display using i2c
 *
 *****************************************************************/
#include <Ultrasonic.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Ultrasonic ultrasonic(9, 8);
#define OLED_RESET 4   //(optional)
Adafruit_SSD1306 display(OLED_RESET);
#if (SSD1306_LCDHEIGHT != 32)     // change it to 64 if you are using 128x64 pixel OLED
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif
void setup()
{
  Serial.begin(9600);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  //display.display();
  //delay(2000);
  display.clearDisplay();
}
void loop ()
{
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.print("Distance: ");
  display.println(ultrasonic.distanceRead());
  display.setCursor(80,0);
  display.print("cm");
  display.display();
  delay(1000);
  display.clearDisplay();
}

 



Downloads:

SR04 Ultrasonic Sensor Module Basics

SR04 Ultrasonic Module Library 

Adafruit GFX Library

Adafruit_SSD1306 OLED Library

Arduino Code

]]>
https://blog.etechpath.com/digital-distance-measuring-device-using-ultrasonic-sensor-sr04-oled-display-and-arduino/feed/ 0
How to interface HC-SR04 Ultrasonic Sensor with Arduino https://blog.etechpath.com/how-to-interface-hc-sr04-ultrasonic-sensor-with-arduino/ https://blog.etechpath.com/how-to-interface-hc-sr04-ultrasonic-sensor-with-arduino/#respond Tue, 03 Apr 2018 23:35:22 +0000 https://blog.etechpath.com/?p=555 About:

HC-SR04 is an Ultrasonic sensor module which includes ultrasonic transmitter, receiver and control circuit in one small PCB.  HC-SR04 has distance measurement ability ranging from 2cm to 400cm. These small units are very accurate and its ranging accuracy can be reach to 3mm.




How HC-SR04 Works:

Ultrasonic modules work on principle similar to radar or sonar. It generates high frequency signal of 40kHz towards object and receives echo signal from subjects surface. Then it can calculate object distance using time interval between the sending of signal and the receiving of echo.




Theory:

To measure the object distance form sensor body we need to send a trigger pulse of 10uS, module will detect the trigger and will send out one 8cycle ultrasonic sound bust of 40kHz towards subject and receives echo of transmitted signal from objects surface. Now you can calculate distance from time interval between sending of signal and receiving of signal.

Distance Calculation:

Time=distance/speed

t = s / v

s = t . v

Speed of sound is 340m/s

v=340m/s = 0.034cm/uS

So, in order to calculate distance in cm, we need to multiply time with 0.034. But in this case time is distance between sensor and object in one way only and in our case the time value we will get from echo will be double because the sound wave needs to travel towards objects and bounce back to sensor. So, in our case the formula will be,

s = t . v/2

s = t . 0.034/2

Circuit Diagram:

Circuit Diagraam

Basic Code:

/*
* Ultrasonic Sensor HC-SR04 and Arduino Tutorial
*
* Crated by Pranay Sawarkar,
* www.eTechPath.com
*
*/
// defines arduino pin numbers
const int trigPin = 9;
const int echoPin = 8;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}







]]>
https://blog.etechpath.com/how-to-interface-hc-sr04-ultrasonic-sensor-with-arduino/feed/ 0