Sunday, November 10, 2013

Ultrasonic Range Finding

Yesterday I got a Sainsmart HC-SR04 Ultrasonic Distance Sensor. This is a very simple to use and very inexpensive sensor that gives accurate range readings up to 400cm or so.

There are 4 wires to connect:

Vcc (5vdc)
Trig (any digital pin)
Echo (any digital pin)

In this example, we will use pins 11 & 12.

You need to download and install the Newping Library from

Then upload the following sketch. This sketch takes the height and radius of a cylinder in centimeters, and outputs a fluid level in liters. The concept here is for a cistern. It tells you how many liters of water are left.

#include <NewPing.h>

#define trigPin 12
#define echoPin 11

const float height = 12.7; //cm
const float radius = 3.81; //cm
float totalCap;
float emptyCap;
float filledCap;

NewPing sonar(trigPin, echoPin);

void setup() {

void loop() {
  int distance = sonar.ping_cm();
  totalCap =(3.142*(radius*radius)*height)*0.001; //Liters
  emptyCap=(3.142*(radius*radius)*distance)*0.001; //Liters
  filledCap =totalCap-emptyCap; //Liters
  Serial.println("Liters Remaining");

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...