I need it to exit the loop whenever any condition mentioned is met. Even when both conditions are not met it stays in the loop. which doesn’t make any sense.
The value of Distance you're showing is greater than 5.
Therefore it doesn't matter what the value of digitalRead(8) is. It won't ever even be read as the boolean expression will short circuit at (distance > 5) because it's true.
Your code says to keep executing the loop while distance > 5.
Distance is greater than 5.
The loop keep executing. Just as you've instructed it to.
If you had a real problem, your output would show something like the following.
Distance: 4
Hole: 0
In that case, distance>5 would be false, ANDdigitalRead(8) would be not equal to HIGH.
And that would be an interesting problem, seeing as you your while condition would have detected that and exited the loop. I suppose it could be displayed once if you managed to have pin 8 go LOW between the test in the while and where it's printed out in the loop. But you'd have to be awfully lucky.
You haven't shown that to be the case.
And I'm said the same thing way too many times already. Someone else want to give it a try? I'm done.
Qubits-us: Those Two conditions represent a distance measuring mechanisms. So which-ever is too close it must stop the motors from going ahead. “And” is not the case here.
Sure, @van_der_decken , I'll give him one, and only one, try.
Look at this code, @vaxman .
It will only ever print, if at least one of the conditions is true. So, you will NEVER see Hole = 0 AND distance <5, because in that specific instance, you don't actually enter the loop.
Hi, @vaxman
Have you got an external pullup resistor on pin8 if your button is between pin8 and gnd?
OR
Have you got an external pulldown resistor on pin8 if your button is between pin8 and Vcc?
if the button is wired between pin and ground and configured as INPUT_PULLUP, it will become LOW while pressed and the logic should be if the distance is far AND the button the is NOT pressed, continue in the loop while ((distance > 5) && (digitalRead(8)== HIGH))
the loop should break if the button is pressed OR the distance becomes close