Nenad Cetic
Published © GPL3+

Ultrasonic Distance Meter

Quick and easy project to teach kids how ultrasonic sensors measure distance. Distance is shown on a mechanical dial - servo motor.

BeginnerShowcase (no instructions)15 minutes2,098
Ultrasonic Distance Meter

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
RobotGeek 180 Degree Robot Servo
RobotGeek 180 Degree Robot Servo
×1

Software apps and online services

Arduino IDE
Arduino IDE

Hand tools and fabrication machines

Lego Bricks

Code

ultrasonic_servo.ino

Arduino
This is a simple example of ultrasonic sensor measurement.
Distance is used to control servo motor.
/*
 This is a simple example of ultrasonic sensor measurement.
 Distance is used to control servo motor.
 */

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0;    // variable to store the servo position

#define servoPin 9
#define trigPin 13
#define echoPin 12

#define MIN_DISTANCE 2
#define MAX_DISTANCE 20
#define MIN_ANGLE 0
#define MAX_ANGLE 180

void setup() {
  Serial.begin (9600);
  myservo.attach(servoPin);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  long duration, distance;
  // Make a Ping
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Get a pulse measurements in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculate the distance - half of the sound wave path.
  // distance = duration / 2 * speed_of_sound
  // 340.29 m/s = 1/29.411 cm/us
  distance = (duration/2) / 29.411;

  if (distance < MAX_DISTANCE && distance > MIN_DISTANCE)
  {
    Serial.println(distance);
    // MIN_DISTANCE cm -> MIN_ANGLE deegrees
    // MAX_DISTANCE cm -> MAX_ANGLE deegrees
    pos = map(distance, MIN_DISTANCE, MAX_DISTANCE, MIN_ANGLE, MAX_ANGLE);
  }
  else
  {
    // if we are getting measurement that dont make sense we will
    // put to servo to closer end position.
    if(pos < (MAX_ANGLE - MIN_ANGLE)/2)
      pos = MIN_ANGLE;
    else
      pos = MAX_ANGLE;
  }
  // Update servo position
  myservo.write(pos);
  delay(10);
}

Credits

Nenad Cetic

Nenad Cetic

5 projects • 42 followers

Comments