Ultrasonic sensor to notice objects and not span the XBee

Hi all I am trying to get my Arduino to notice if there is a object in front of it using an ultrasonic sensor but when I run this code it seems to spam the XCTU with Object Found how can I change the code to not spam this. My programming skills are not great any help would be appreciated!

SoftwareSerial XBee (3,2);

#define trigPin 8
#define echoPin 9

int objectcount = 0;

void setup(){
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

void loop(){

long duration, distance; //building the calculation for the ultrasonic sensor
digitalWrite(trigPin, HIGH);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance <12){
objectcount = objectcount + 1;
if (objectcount < 2){ =i
XBee.write(“Object Found”);
objectcount = 0;


Send a message when an object becomes detected, not when it's detected. Hint: for that you need to know the past state.

Suppose that there IS something close. Look carefully at what you do. You increment the count of objects close, you send a message, and then you set the count to 0 again. How many close objects will there ever be?

Why are you surprised that the number of close objects is always reported as one?