Counting when switching state

Hello,

I need a code collecting data for how often a parking lot is occupied
I'm using an ultrasonic sensor. If the object is within 5 centimeters the parking lot is occupied otherwise it is unoccupied.
Every time a new object is occupying the parking lot, the counter has to add one to the previous counted amount.

The code I have created so far

#define led_red_pin 11
#define led_green_pin 9
#define trigPin 7
#define echoPin 5

int count;

float duration, distance;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(led_red_pin, OUTPUT);
  pinMode(led_green_pin, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);

  distance = (duration / 2) * 0.0343;
 
  if (distance >= 5) {
    Serial.println("Unoccupied");
    digitalWrite(led_red_pin, LOW);
    digitalWrite(led_green_pin, HIGH);
    Serial.println(distance);
    delay(1000);
  }
  else if (distance <= 5 || distance >= 2) {
    Serial.println("Occupied");
    digitalWrite(led_red_pin, HIGH);
    digitalWrite(led_green_pin, LOW);
    count++;
    Serial.println(count);
  }
}

Hope you can help!

Thanks for posting your code properly, using code tags!

Now, please tell us which ultrasonic sensor you are using, explain what the code should do, and what it does instead.

The specific sensor is: an ultrasonic HC-SR04 sensor

I want the code to count every time the parking space goes from "occupied" to "unoccupied", meaning it should only count when a new object uses the parking space

At the moment the code adds one to the counter every 1 second while the same object occupies the parking space

Hope it makes sense now

You need to increment the count when the space becomes occupied rather than when it is occupied

Have look at the StateChangeDetection example in the IDE