Car counter

Hello Arduino community

Blh64 was very nice helping me fixing my code and is working, now I have other question.

I´m trying to count the number of cars that is passing trough the sensor, from cero to 3 meters away. The thing is: it makes the count for the time the car is passing, and with the delays could be fixed but not all the cars are the same size…

Can you please help me

Thank you

#include <DFRobot_TFmini.h>

SoftwareSerial mySerial(12, 13); // RX, TX

DFRobot_TFmini  TFmini;
uint16_t distance,strength;
int count=0;

void setup(){
    Serial.begin(9600);
    TFmini.begin(mySerial);
}

void loop(){
    if(TFmini.measure()){                      //Measure Distance and get signal strength
        distance = TFmini.getDistance();       //Get distance data
        strength = TFmini.getStrength();       //Get signal strength data
     
    }
       if(distance<300){
        count++;
       
        Serial.print("Distance = ");
        Serial.print(distance);
        Serial.println("cm");
        Serial.print("Contador:");
        Serial.println(count);
        //Serial.print("Strength = ");
        //Serial.println(strength);
        //delay(5000);
        }
        
}

"the sensor"... if you are going to start a new thread, realize that most people will not have seen the first one. So you have to start all over with a full description of everything.

The sensor is a TF mini plus, its an infrared sensor that it measures from .5 cm to 12 meters.

The board is an Arduino uno

and this was the first post:

Hello Arduino community,
I´m a beginner in this, so please understand if I make mistakes.
I been fighting with the cheap infrared sensors and I change them for this TF mini plus, it looks like they work good.
In my code it measures the distance, then I try to only print the distance if its under certain number, but for some reason it print the distance above or under the certain number.
Can you help me please?
thank you

You need a flag to say if you have already detected the car or not…

//declare a global...
bool bCarPresent;

//then to check car BECOMING present...
if(distance<300 && bCarPresent==false){
  bCarPresent = true;
  ....
}

//and to check car BECOMING absent...
if (distance>=300 && bCarPresent==true) {
  bCarPresent = false;
  ....
}

It might help if you add some hysteresis. Hysteresis is a slightly lower threshold for detecting presence of the car from absence. This means that if the sensor value fluctuates around the threshold with the car present, you won’t detect more than one car.

You guys are genius, you can make anything in this world! thank you so much

Look up state machines