help with programming photovore if statment

Hi everyone,

I am new to the Arduino platform and programming in general. I am trying to make a photovore robot with 2 photo resistors and 2 servos and it works ok. but it will not go forward. heres the relevant section of code.

if(analogValueR == analogValueL)
 {
   servoMotorR.write(179);                       
   servoMotorL.write(0);
 }
   
    if(analogValueL < analogValueR)
 {
   servoMotorR.write(0);                      
   servoMotorL.write(0);
 }
 
   if(analogValueR < analogValueL)
 {
   servoMotorR.write(179);                      
   servoMotorL.write(179);
 }
   delay(15);                                         
 }

I realize that it is not going forward because the value of each photocell will almost never be equal so my question is how to I get the if statement to allow the servos to go forward with the photo resistors being within say 100 units of each other?

thanks in advance! :smiley:

@ jediryan123

photo resistors being within say 100 units of each other

Maybe test the absolute value of the difference with something like

unsigned threshold = 100; // How close they have to be to be considered "nearly equal"
.
.
.
void loop()
{
.
.
.
    if(abs(analogValueR - analogValueL) < threshold) // They are nearly equal
    {
        // Whatever you need to do if they are "nearly equal"
    }

    else // They are not nearly equal
    {
        if(analogValueL < analogValueR)
        {
            //Whatever you do if they are not "nearly equal" and L < R
        }
        else
        {
            //Whatever you do if they are not "nearly equal" and R > L               
        }
    }
.
.
.
}

By making the "threshold" a variable (and not buried inside the logic in the conditional statement), it's easy to see how to experiment with different thresholds by simply changing that declaration to make it equal to some other value.

Regards,

Dave

thanks Dave that code worked brilliantly, heres a video of the finished product.

@jediryan123

finished product.

I love it!

Thanks for the feedback.

Regards,

Dave

Footnote:
Onward and upward!