Cirkit Designer LogoCirkit DesignerYour all-in-one circuit design IDE Launch Cirkit Designer App

ESP8266 NodeMCU Controlled Ultrasonic Distance Measurement

View and Edit Project In Cirkit DesignerImage of ESP8266 NodeMCU Controlled Ultrasonic Distance Measurement

Circuit Documentation

Summary of the Circuit

This circuit integrates an ESP8266 NodeMCU microcontroller with an HC-SR04 Ultrasonic Sensor to measure distances. The ESP8266 NodeMCU is programmed to trigger the HC-SR04 to send an ultrasonic pulse and then listen for the echo. The time taken for the echo to be detected is used to calculate the distance to an object. The ESP8266 NodeMCU is also configured to connect to a Wi-Fi network and send the measured distance to a server.

Component List

ESP8266 NodeMCU

HC-SR04 Ultrasonic Sensor

Wiring Details

ESP8266 NodeMCU

HC-SR04 Ultrasonic Sensor

Documented Code

ESP8266 NodeMCU Code

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "DHAIRYA";
const char* password = "DHAIRYA108!@#shah";

const char* serverAddress = "http://yourServerAddress/update"; // Your server's address

// HC-SR04 pins
const int trigPin = D1;
const int echoPin = D2;

WiFiClient client;
HTTPClient http;

void setup() {
  Serial.begin(115200);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1; // Speed of sound wave divided by 2 (go and back)

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  if (WiFi.status() == WL_CONNECTED) {
    http.begin(client, serverAddress);
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    String httpRequestData = "distance=" + String(distance); // Your HTTP request's data
    int httpResponseCode = http.GET(httpRequestData);

    if (httpResponseCode > 0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
    } else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }
    http.end();
  } else {
    Serial.println("WiFi Disconnected");
  }
  delay(1000); // Send a request every second
}

HC-SR04 Ultrasonic Sensor Code

The HC-SR04 Ultrasonic Sensor does not have its own code as it is not a programmable device. It is controlled by the ESP8266 NodeMCU as described in the code above.