DEV Community


Arduino Distance Sensor

Kyle Trahan
Full Stack Software Engineer
・2 min read

I finally got my Arduino distance sensors in the mail. This is my first time expanding my knowledge outside of the beginners tutorial book. As I have been working through the tutorial book I was trying to think of what I wanted my first real project to be. As an end goal I want to try and make a robot from scratch that will essentially act like a roomba, but rather than being a floor cleaning slave, my robot will just wonder around the house aimlessly contemplating the finer things in life. Like which walls to not run into. I figured my first step would be figuring out how to give my robot eyes. This landed me on getting a few Ultrasonic Sensors to start playing around with. These sensors work kind of like a bat or a dolphin using echo location in order to determine how far something is from its sensors. The basic goal would be to keep the robot from running into walls by setting a designated minimum distance in which to tell the robot to turn.

I started off really simple and just set up the sensor on my bread board and moved different objects in front of it to test the sensors reach. I was able to get to about 10 feet away before it started to get a little wonky. So this should work just fine at a small distance of an inch or two. The coding for it was pretty simple. Ill go over that a little more below.

I'll skip all the boring parts like hooking up the power and the ground. The two new pins for me are a trigger pin and an echo pin. Basically the trigger pin will go from off to on to off again. This basically sends off a sonic burst that will travel until it hits something and then it returns back to the sensor. Then the echo pin works its magic by receiving that burst and translating it into the computer to let us know how long it took to travel. There is a little bit of math that gets done with the duration in order to figure out just how far we traveled. You take your duration and multiple that by the speed of sound or 340 m/s ( .034 cm/microsecond) and then divide that by two, since the sound is traveling there and back it actually gives us double the duration we need. The code below will go over how that happened:

void loop() {
  digitalWrite(triggerPin, LOW);
  digitalWrite(triggerPin, HIGH);
  digitalWrite(triggerPin, LOW);
  duration = pulseIn(echoPin, HIGH);

    distance = duration * .034 / 2;

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

Enter fullscreen mode Exit fullscreen mode

Im very excited to get the next piece of my robot puzzle together. I will probably start to get more into the motors and figuring out how to make the wheels work.

Discussion (0)