Go Down

Topic: Servo motor rotating randomly (Read 226 times) previous topic - next topic

progamerdhruv1

May 23, 2020, 06:38 pm Last Edit: May 23, 2020, 06:40 pm by progamerdhruv1
I tried using servo motor with arduino and ultrasonic sensor HC-SR04.

The basic idea behind this project was to attach the ultrasonic sensor to the servo so that it sweeps an area and work like SONAR.

But when the Arduino UNO R3 is powered up, it just start rotating randomly.

This is a strange thing because when I remove all the code dealing with the HC-SR04, The servo works just fine(no random movements and vibrations).

MY CODE:

Code: [Select]

const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;
int pos = 0;
#include <Servo.h>
Servo myservo;
void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600); // Starts the serial communication
  myservo.attach(6);
}
void loop() {
  for (pos = 0; pos <= 180; pos += 1) {
    myservo.write(pos);
    delay(15);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = duration * 0.034 / 2;
    Serial.print("Distance: ");
    Serial.println(distance);
  }

  for (pos = 180; pos >= 0; pos -= 1) {
    myservo.write(pos);
    delay(15);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = duration * 0.034 / 2;
    Serial.print("Distance: ");
    Serial.println(distance);
  }

}

slipstick

Pinging an ultrasonic sensor roughly every 15ms is pushing your luck. Maximum of 20Hz i.e. 50ms is usually recommended. And pinging it every 1 degree of movement is probably pointless. Try changing the pos increment to 10 or 15 degrees and the delay between moves to delay(50) and see what that does.

Steve

progamerdhruv1

Thanks brother, this solution worked just as I wanted!

Go Up