Skip to main content

Command Palette

Search for a command to run...

Height Measurement Using Ultrasonic sensor

Updated
1 min read

height measurement

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2); // Change 0x27 to 0x3F if not working

#define TRIG 9
#define ECHO 10

// Height of sensor from ground in cm
int sensorHeight = 200;   

void setup() {
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);

  lcd.init();
  lcd.backlight();
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Height Meter");
  delay(1500);
}

long getDistance() {
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);

  long duration = pulseIn(ECHO, HIGH);
  long distance = duration * 0.034 / 2; // in cm
  return distance;
}

void loop() {
  long distance = getDistance();

  // Calculate height 
  long height = sensorHeight - distance;

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Dist: ");
  lcd.print(distance);
  lcd.print(" cm");

  lcd.setCursor(0, 1);
  lcd.print("Height:");
  if (height > 0 && height < 250) {
    lcd.print(height);
    lcd.print(" cm");
  } else {
    lcd.print("Out of range");
  }

  delay(500);
}

More from this blog

Aarav's Blogs

19 posts