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:
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);
}
}