I am working on an autonomous RC car (Autonomous RC car guided by GPS coordinates - project thread - #6 by system - Project Guidance - Arduino Forum). For obstacle avoidance, I am using a PING ultrasonic sensor mounted on a servo that sweeps back and forth. While I can get the servo and the sensor to work fine independently, I can't get them to work together. I think it is due to a problem with my wiring. Any ideas on how to solve it?
Here is the wiring used in all cases.

Alone, the servo works.
#include <Servo.h>
Servo sensingServo;
int pos = 1300;
void setup()
{
Serial.begin(9600);
sensingServo.attach(5);
}
void loop() {
//SWEEP
// results in roughly one over and back pass each second
// at a resolution of 36 measurements for each pass
for(pos = 800; pos < 1700; pos += 25)
{
sensingServo.writeMicroseconds(pos);
Serial.print("Position: ");
Serial.print(pos);
Serial.print("\n");
}
for(pos = 1700; pos > 800; pos -= 25)
{
sensingServo.writeMicroseconds(pos);
Serial.print("Position: ");
Serial.print(pos);
Serial.print("\n");
}
}
Alone, the sensor also works.
#include <Servo.h>
// setup ultrasonic distance sensor
const int pingPin = 2;
unsigned int duration, distance;
void setup() {
Serial.begin(9600);
}
void loop() {
// read and print ultrasonic sensor distance
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
distance = duration / 74 / 2;
Serial.print(" Distance: ");
Serial.print(distance);
Serial.print("\n");
}
But, when I try to put them together, the servo sweeps erratically and the sensor outputs bad data. Any ideas about how to fix the issue?
#include <Servo.h>
Servo sensingServo;
int pos = 1300;
// setup ultrasonic distance sensor
const int pingPin = 2;
unsigned int duration, distance;
void setup()
{
Serial.begin(9600);
sensingServo.attach(5);
}
void loop() {
for(pos = 800; pos < 1700; pos += 25)
{
sensingServo.writeMicroseconds(pos);
// read and print ultrasonic sensor distance
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
distance = duration / 74 / 2;
Serial.print("Position: ");
Serial.print(pos);
Serial.print(" Distance: ");
Serial.print(distance);
Serial.print("\n");
}
for(pos = 1700; pos > 800; pos -= 25)
{
sensingServo.writeMicroseconds(pos);
// read and print ultrasonic sensor distance
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
distance = duration / 74 / 2;
Serial.print("Position: ");
Serial.print(pos);
Serial.print(" Distance: ");
Serial.print(distance);
Serial.print("\n");
}
}
Thanks for your help.
