keeping right distance with the HC-SR04

Hey guys,

I’m new to the forum and don’t know if there is allready a thread for a problem like this, but I would like to see if you guys can help me out :grinning:

I’m trying to make small vehicle move at the right distance from a object. My set-up consists of a HC-SR04 ultrasonic sensor, a small dc-motor and a h-bridge.

The problem that I have has to do with the code. Underneeth you can see the short void loop I’ve got going right now and I’ve marked where the problem is;

void loop() {
  digitalWrite(onOff, LOW);
  digitalWrite(trigPin, LOW);
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 2.91;
  if (distance < 2000) {
    Serial.print("distance: ");
  else {
    Serial.print("distance: ");
    Serial.println("OUT OF RANGE");

  if (100 <= distance <= 180) {                  // THIS IS THE PART WHICH I CAN'T FIGURE OUT
    digitalWrite (directionL, LOW);
    digitalWrite (directionR, LOW);
    Serial.print("motor off    ");

  if (distance < 100) {
    digitalWrite (directionL, HIGH);
    digitalWrite (directionR, LOW);
    Serial.print("motor left  ");

  if (distance > 180) {
    digitalWrite (directionL, LOW);
    digitalWrite (directionR, HIGH);
    Serial.print("motor right ");



My problem is, whenever the distance is lower or higher then 100 or 180, my program will allways print "motor off " because that’s valid.

Can you guys tell me how to tackle this problem. I’m kinda new to programming with arduino and my english isn’t the greatest. But I can use all the help!!

Thanks allot and have a good night :smiley:

if (100 <= distance <= 180)this one comes up about once a week.
I’m fed up of explaining it.

Use &&

You don’t even need to figure it out. Use an if / else if coding. You’ve got a test for below 100 and a test for above 180. So if both of those are false then the only other option is that it is between the two. So that could just be an else statement.

if (x < 100) {do something}
else if (x > 180) {do something else}
else {do something since it is in between}