Please edit your post and use code tags for the code
Type
** **[code]** **
before the code
Type
** **[/code]** **
after the code
I think what you want is a function that returns a value. Looking at this
void SonarSensor(int trigPin, int echoPin)
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
}
you're only interested in the distance. You're function can return the distance.
/*
read sonar distance
input:
trigger pin
echo pin
returns:
distance in cm
*/
long SonarSensor(int trigPin, int echoPin)
{
...
...
Next you can do the calculation as you did
/*
read sonar distance
returns:
distance in cm
*/
long SonarSensor(int trigPin, int echoPin)
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
// return measured distance
return distance;
}
And in e.g. loop()
void loop()
{
// get the distance
RightSensor = SonarSensor(trigPin1, echoPin1);
Serial.print("distance = "); Seral.println(RightSensor);
}
Now I would clean the function up a little. Nowhere in your code you will be interested in the duration. So instead of making that a global variable, you can declare it inside the function (local variable).
long SonarSensor(int trigPin, int echoPin)
{
// variable to hold measured duration
long duration;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
// return measured distance
return distance;
}
And remove the duration from the global variables near the top of the code.
#define trigPin1 11
#define echoPin1 12
//WAS: long duration, distance, RightSensor, BackSensor, FrontSensor, LeftSensor;
long distance, RightSensor, BackSensor, FrontSensor, LeftSensor;
...
...
You can do the same for distance; I would make it a local variable in the SonarSensor function and get rid of it in the global section.
Note
At the moment that you start numbering variables (e.g. trigPin1), it's time to consider arrays.