State machine: what the program remembers
A sensor only tells you what is true now. To close a gate three seconds after a car has gone, the program must remember which state it is in: closed, open, or waiting to close. A program built that way is a state machine, and engineers draw it as a state chart: a box for each state, an arrow for each thing that makes it change.
Keep the state in a variable (like gateOpen), change it only when something happens, and act on it every loop.
More: state chart or flow chart, and counting something once
A flow chart shows the steps of the program one after the other. A state chart shows the states and what moves the machine from one to the next; it does not care how many lines of code that takes. Traffic lights, washing machines, lifts, games (playing, paused, game over) and robots are all state machines.
The same idea counts a car once. The loop runs ten times a second, so a car that stands in front of the sensor for two seconds is "near" twenty times. Remember what the sensor said last time: the car has driven past when it was near last time and is not near now. That is a tiny state machine too, with two states: no car, car.
bool carWasNear = false; // the state of the sensor last time round int cars = 0; void loop() { bool near = sensor.measureDistanceCm() < 15; if (carWasNear && !near) { // near before, not near now: a car drove past cars = cars + 1; } carWasNear = near; // remember for the next loop delay(100); }
The same gate as a flow chart: the steps, not the states. Draw both for your program and compare.