Thanks for posting the code.
I think this part sends one "ping" each time round the loop, measures the echo duration, prints some values and then waits 100ms. Are you getting sensible answers from the print statements?
long duration, inches, cm;
pinMode (trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
inches = microsecondsToInches(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
Next, the while loop will not work the way it is written. Remove the while loop for now. Also remove the next pulseIn statement. You already have a value in duration.
while (millis() < 1000) {
duration = pulseIn(echoPin, HIGH);
When you remove the while loop, remember to remove the closing "}" (the one before "aproach =").
Just remove the loop, do not remove this code which is in it. It looks to be doing what you need - finding the maximum and minimum durations since the program started running.
// record the maximum sensor value
if ( duration > durationMax) {
durationMax = duration;
}
// record the minimum sensor value
if ( duration < durationMin) {
durationMin = duration;
}
But I am confused about what you do next.
aproach = durationMax - durationMin;
if (aproach > threshold1)
{
motors.setSpeeds(0, 200);
}
else {
motors.setSpeeds(0, 0);
}
The variable "aproach" will get bigger if the spread of echo durations gets bigger. So you adjust the motor speed. But if this is meant to change the echo durations, there is nothing to reduce aproach - it can only stay the same or get bigger.
Can you tell us what the program is trying to do in real world terms? What are you pinging, what are you controlling?
Thanks
Ray