Hi,
I need help. I trying to learn how to program the arduino. I am currently involved in making a dodging robot. I am using 4 ping sensors to detect the distances. After detecting that, I do a comparison between the distances to find out which one is the farthest, then the corresponding direction PIN is set to HIGH. The problem is that this code is executing very slowly. I was wondering if any changes could be made to the code to make it execute fast. Right now its taking almost 5 seconds to output a HIGH.
please help! I got some of this code in the forum.
int ultraSoundSignalPins[] = {2,3,4,5}; // Left,Front, Front Right, Rear Ultrasound signal pins
char *pingString[] = {"Left ","Front ", "Right ", "Rear "}; // just something to print to indicate direction
int farthest_Dist=ping(0);
int pinFWD=7;
int pinREAR=8;
int pinLEFT=9;
int pinRIGHT=10;
void setup()
{
Serial.begin(9600);
pinMode(pinFWD,OUTPUT);
pinMode(pinREAR,OUTPUT);
pinMode(pinLEFT,OUTPUT);
pinMode(pinRIGHT,OUTPUT);
}
void loop()
{
unsigned long ultrasoundValue;
for(int i=0; i < 4; i++)
{
ultrasoundValue = ping(i);
Serial.print(pingString*);*
-
Serial.print(ultrasoundValue);*
-
Serial.print("in, "); *
-
Serial.println();*
-
}*
-
{*
-
{*
-
if (ping(1) > ping(0))*
-
{*
-
farthest_Dist=ping(1);*
-
digitalWrite(pinFWD,HIGH);*
-
}*
-
else if (ping(2)>ping(0))*
-
{*
-
farthest_Dist=ping(2);*
-
digitalWrite(pinRIGHT,HIGH);*
-
}*
-
else if (ping(3) > ping(0))*
-
{*
-
farthest_Dist=ping(3);*
-
digitalWrite(pinREAR,HIGH);*
-
}*
-
else if (ping(0)==ping(1)==ping(2)==ping(3))*
-
{*
-
digitalWrite(pinLEFT,LOW);*
-
digitalWrite(pinFWD,LOW);*
-
digitalWrite(pinRIGHT,LOW);*
-
digitalWrite(pinREAR,LOW);*
-
}*
-
else*
-
{*
-
farthest_Dist = ping(0);*
-
digitalWrite(pinLEFT,HIGH);*
-
}*
Serial.print (farthest_Dist);
- Serial.println();*
- }*
- }*
}
//Ping function
unsigned long ping(int i)
{
- unsigned long echo;*
_ pinMode(ultraSoundSignalPins*, OUTPUT); // Switch signalpin to output*_
_ digitalWrite(ultraSoundSignalPins*, LOW); // Send low pulse*
* delayMicroseconds(2); // Wait for 2 microseconds*
digitalWrite(ultraSoundSignalPins*, HIGH); // Send high pulse*
* delayMicroseconds(5); // Wait for 5 microseconds*
digitalWrite(ultraSoundSignalPins*, LOW); // Holdoff*
pinMode(ultraSoundSignalPins*, INPUT); // Switch signalpin to input*
digitalWrite(ultraSoundSignalPins*, HIGH); // Turn on pullup resistor*
echo = pulseIn(ultraSoundSignalPins*, HIGH); //Listen for echo*
return (echo / 58.138) * .39; //convert to CM then to inches_
}