1

This code is measuring distance from object by using the Ultrasonic Sensor and print onto serial monitor.

However, serial monitor constantly output values. I want to print only one time if detected value not change. and serial monitor print again only when detected value change. and The above condition keeps repeating.

How can i change the code?

int distance ;
int trig = 3;
int echo = 2;

void setup()
{
  Serial.begin(9600);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
}

void loop()
{
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  distance = pulseIn(echo, HIGH) / 58;
  Serial.println(distance); 
}
2
  • the loop() block keeps repeating over and over ... think about how you would remember what the value of "distance" was the last time around
    – jsotola
    Commented Sep 27, 2019 at 3:53
  • Store the distance in another variable, like int distanceValue; and then you can do this: if(distance != distanceValue){Serial.println(distance); distanceValue = distance;}. Commented Sep 27, 2019 at 7:21

1 Answer 1

1
int distance;
int last_distance; // <== To hold the value from the previous pass
int trig = 3;
int echo = 2;

void setup()
{
  Serial.begin(9600);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
}

void loop()
{
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  distance = pulseIn(echo, HIGH) / 58;
  if (distance != last_distance) {  // <== Check if new distance is different
    Serial.println(distance);       //     Print only if the values are different
  }
  last_distance = distance;         // <== Store this loop's distance for next round
}
1
  • I recommend AGAINST providing fully functional code for beginner questions. When you do that newbies tend to copy/paste the solution without understanding it. It's more work for both you and the OP if you tell them how to solve it and then support them as they work through it, but ultimately the questioner learns more that way.
    – Duncan C
    Commented Sep 27, 2019 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.