 # define names

hello

Im duing a project where I want my roomba robot to drive forward when it
receives a ping from the ultrasonic transmitter.

The speed of the roomba is ditected by the distance from the ultrasonic

I’ve made 3 functions to call depending on how far the distance is.

The distance is showed in the serial monitor and I want to use that information

to make the robot drive in the called velocity.

my problem is that I want to define the distance as:

distance = a, where the distance is =
cm

so it will work with my if / else statements

// if (a >= 40 || a <120) // 40 cm or 120 cm
{
forwardnormal();
}

if (a <40)
{
forwardslow();
}

if (a >120)
{
forwardfast();

Best regards

my problem is that I want to define the distance as:

distance = a, where the distance is = cm

You mean like `int distance = a;` ?

my problem is that I want to define the distance as:

Why is that a problem? What does your code really look like? What is not working?

Not sure what the issue is, but the way the code is written, two unnecessary if tests are going to be executed on each pass through the loop. Why not use something like:

``````int distance;

if (distance >= 40 && distance <= 120)
{
ForwardNormal();
} else {
if (distance < 40)
{
ForwardSlow();
} else {
ForwardFast();
}
}
``````

As a general rule, anytime you have a situation where one of the conditions prevails more often than the others, place its test first. That way, you avoid the remaining tests. As your code is written, if the first condition is true, the remaining if conditions must be false, which means they are executed unnecessarily. Nested if statements as shown here avoid the redudant if tests when the first condition is true.