Ultrasonic sensor not measuring distances properly

I'm working on a small project where a servo will turn when something is placed within 5cm of an ultrasonic sensor.

My code:

#define TURN_TIME 175
#include <Servo.h>
#define trigPin 7
#define echoPin 6
Servo myservo;
int sound = 250;

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

void loop() {

long duration, distance;
digitalWrite(trigPin, LOW);
digitalWrite(trigPin, HIGH);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;

if (distance < 5) {
Serial.println("the distance is less than 5");

else {

if (distance > 60 || distance <= 0){
Serial.println("The distance is more than 60");
else {
Serial.println(" cm");

My problem is that when I run the code my ultrasonic sensor alternates outputting distance is less than 5cm and distance is more than 60, no matter the distance of the object in front of the sensor. This also causes the servo to turn every second. From what i can see the connections into the Arduino are fine. Let me know if you need more info, TY.

What made you think that your question has anything to do with the Website and Forum section which is clearly stated to be for "Improvements for the web system, applications to moderator, spam, etc."? I have suggested to the Moderator to move it to the Programming section.

This sort of carelessness makes unnecessary work for the Moderators.


You need supply decoupling between the motors and the sensors. You are probably getting interference between the two.

How is it without the servos attached?

You are treating a distance of zero (no echo pulse received) as both <5 and <=0 so if you don't get an echo you will show both messages.

Note: The default timeout for pulseIn() is 1,000,000 microseconds (1 second). You can pass a third argument to pulseIn() to shorten it to something like 20000 (20 milliseconds) so if no echo is seen it doesn't take a full second to find out.