I've got an HC-SR04 Ultrasonic range detector mounted on a servo. It rotate, scan and store 3 values (45, 90 and 135 degrees)
Now i want that it can compare the 3 values to choose the longest distance. I used an if..else loop to let is choose but is there any way that works better. Because now it compares 45 with 90 and 135 with 90 degrees. But if the first string (45>90) is true, it won't check (135>90).
Here's my sketch:
void loop()
{
myservo.write(45);
delay(1000);
int microsec45 = ultrasonic.timing();
Serial.print("MS45: ");
Serial.print(microsec45);
myservo.write(90);
delay(1000);
int microsec90 = ultrasonic.timing();
Serial.print("MS90: ");
Serial.print(microsec90);
myservo.write(135);
delay(1000);
int microsec135 = ultrasonic.timing();
Serial.print("MS135: ");
Serial.print(microsec135);
for(pos = 135; pos>=45; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
if (microsec45 > microsec90)
{
digitalWrite(ledpin43, HIGH); // set the LED on
delay(1000); // wait for a second
digitalWrite(ledpin43, LOW); // set the LED off
}
else if (microsec135 > microsec90)
{
digitalWrite(ledpin13, HIGH); // set the LED on
delay(1000); // wait for a second
digitalWrite(ledpin13, LOW); // set the LED off
}
else
{
digitalWrite(ledpin13, HIGH); // set the LED on
digitalWrite(ledpin43, HIGH); // set the LED on
delay(1000); // wait for a second
digitalWrite(ledpin13, LOW); // set the LED off
digitalWrite(ledpin43, LOW); // set the LED off
}
I used the 2 led pins on my Uno32 in stead of dc motors, to make it move visible what choices it makes.
It might work better to determine the highest as you're reading them. Then you can just compare the current reading to the highest reading thus far. Something like this:
void loop()
{
byte deg[] = { 45, 90, 135 };
int readings[ 3 ] = { 0 };
int highReading = 0;
int furthest;
boolean light45 = false;
boolean light135 = false;
for( int i = 0; i < 3; i++ )
{
myservo.write( degs[ i ] );
delay( 1000 );
readings[ i ] = ultrasonic.timing();
if( readings[ i ] > highReading )
{
highReading = readings[ i ];
furthest = i;
}
}
if( furthest < 2 ) // either 45 or 90
{
digitalWrite( pinFor45, HIGH );
}
if( furthest > 0 ) // either 90 or 135
{
digitalWrite( pinFor135, HIGH );
}
delay( 1000 );
digitalWrite( pinFor45, LOW ); // don't need to test to turn off, since there's no harm in turning off one that's already off
digitalWrite( pinFor135, LOW );
}