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);
}
int distanceValue;
and then you can do this:if(distance != distanceValue){Serial.println(distance); distanceValue = distance;}
.