Hey all, I couldn't find anything online or on the forum about this issue.
I am trying to use multiple PING))) sensors with my vehicle's servo motor for obstacle avoidance (my vehicle is a Traxxas E-Maxx RC car). I have been working with code from another of my posts (http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1236272388) and added a controller part for testing the servos. My current code is shown below.
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int ultraSoundSignalPins[] = {7,8,9,12}; // Front Left,Front, Front Right, Rear Ultrasound signal pins
char *pingString[] = {"Front Left ","Front ", "Front Right ", "Rear "}; // just something to print to indicate direction
void setup()
{
myservo.attach(10); // attaches a servo to pin 10
Serial.begin(9600);
}
void loop()
{
unsigned long ultrasoundValue;
for(int i=0; i < 4; i++)
{
ultrasoundValue = ping(i);
Serial.print(pingString[i]);
Serial.print(ultrasoundValue);
Serial.print("in, ");
delay(50);
}
Serial.println();
delay(50);
if(ping(1) < 20)
{
myservo.write(35);
}
else
{
myservo.write(90);
}
}
//Ping function
unsigned long ping(int i)
{
unsigned long echo;
pinMode(ultraSoundSignalPins[i], OUTPUT); // Switch signalpin to output
digitalWrite(ultraSoundSignalPins[i], LOW); // Send low pulse
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(ultraSoundSignalPins[i], HIGH); // Send high pulse
delayMicroseconds(5); // Wait for 5 microseconds
digitalWrite(ultraSoundSignalPins[i], LOW); // Holdoff
pinMode(ultraSoundSignalPins[i], INPUT); // Switch signalpin to input
digitalWrite(ultraSoundSignalPins[i], HIGH); // Turn on pullup resistor
echo = pulseIn(ultraSoundSignalPins[i], HIGH); //Listen for echo
return (echo / 58.138) * .39; //convert to CM then to inches
}
The problem is that this does not work well with the vehicle. After uploading, the wheels just keep going from 90 to 35 to 90, etc. The results from the serial monitor can be seen below. They were also printing out really sporatically.
Front Left 126in, Front 0in, Front Right 0in, Rear 61in,
Front Left 0in, Front 70in, Front Right 53in, Rear 61in,
Front Left 73in, Front 0in, Front Right 14in, Rear 61in,
However, when I was debugging the code I switched from using the servos to the drive motors by adding pinMode(11, OUTPUT); to the void setup() section and replacing the if/else servo statement in the void loop() section with the following
if(ping(1) < 20)
{
analogWrite(11, 190); //stop
}
else
{
analogWrite(11, 196); //move forward
}
After uploading it to the Arduino I discovered this code works perfectly fine and the serial monitor prints out great >:(.
Anyone got any ideas as to why the servo code is not working? Any help if greatly appreciated.