Distance-aware machine

Today was about testing a setup where a machine is able to determine how far an object is from it and then control a servo motor to avoid touch. Two challenges that I faced with this was that the ultrasonic sensor I used for measuring distance won’t fix on the servo motor’s head and the servo motor could only go 180 degrees. As a result, the sensor was placed separatly and the main idea didn’t materialize. However, the concept suceeded, leaving only the physical setup to be mastered at another time.

Along witht the usual bread board and jumper cables, I used the following for the test:

  • Arduino Uno (cheap Chinese copy)
  • Ultrasonic sensor (HC-SR04)
  • Servo motor (SG90)

As you can see, the connections are pretty simple, VCCs to the 5V supply, GNDs to the ground. 3 digital pins for the remaining input and outputs. Here is the source code.

#include <Servo.h>

Servo myservo;

const int trigPin = 3;
const int echoPin = 4;

long duration;
int distance;
int angle;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

void loop() {
  digitalWrite(trigPin, LOW);
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance= duration * 0.034 / 2;
  angle = map(distance, 0, 30, 0, 180);

  if (angle > 180) { angle = 180; }
  Serial.print(", ");

The ultrasonic sensor is controlled by the Arduino to send ultrasonic waves each time the trigger is fired. The sensor reads back the waves sent and this allows us to determine the duration it took for the wave to return. The duration is directly related to how far an object is from the sensor – the exact relation being 0.034/2 for the sensor I used, as noted in the code above.

The calculated distance is converted to an angle using the map function with the limit being 0 as minimum and 30 as maximum, “mapped” to upto 180 degrees. The 30 was derived from testing the serial inputs used for monitoring the distance and associated angle. It represents a close enough distance to see major changes in the servo’s angle without moving the object infront of the sensor, i.e. smaller movements lead to larger angle changes. This also made the motor “jittery”, even more than the usual for the ultrasonic sensor’s own jitteriness. However, it was a necessary step to demo the concept.

Here is what it looks like when recorded from a camera:

Note: this short video was made at a different iteration of the testing and the code varied slightly from the one shown in the post.

Leave a Reply

Your email address will not be published. Required fields are marked *