Help on Speed trap using 2 ultrasonic sensors

I haven´t ever taking any sort of arduino classes but i got interested in making a sort of "speed trap" that works by having two ultrasonic sensors and measuring the time it takes the object to cross both sensors however i just don´t know what to do in this situation and any help would be highly apreciated

#include<chrono>
using namespace std::chrono;

#define trigPin1 27
#define echoPin1 14
#define trigPin2 33
#define echoPin2 32

float velocidad;
float tiempo;
float distancia = 14; //cm

long duration1;
float distance1;
float stDistance;
long duration2;
float distance2;
float ndDistance;


void setup() {
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(trigPin2, INPUT);
  Serial.begin(9600);

}

void loop() {
  // Clears the trigPin
  digitalWrite(trigPin1, LOW);
  digitalWrite(trigPin2, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin1, HIGH);
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin1, LOW);
  digitalWrite(trigPin2, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration1 = pulseIn(echoPin1, HIGH);
  duration2 = pulseIn(echoPin2, HIGH);
  // Calculating the distance
  distance1 = duration1 * 0.034 / 2;
  distance2 = duration2 * 0.034 / 2;
  // Prints the distance on the Serial Monitor
  stDistance = distance1;
  ndDistance = distance2;
  
  if (distance1 < stDistance){  //object passes in front of 1st sensor
    auto startTime = steady_clock::now(); //starts timer
    if (distance2 < ndDistance){ //object passes in front of the 2nd sensor
      auto endTime = steady_clock::now();//ends timer
      auto tiempo = (endTime - startTime); //calculates diference
      duration_cast<miliseconds>(tiempo).count(); //gives time in miliseconds
      velocidad = ((distancia/tiempo)*10); // multiplies x10 to turn cm/ms to m/s
      printf("Velocidad = ", velocidad, "m/s"); // prints the m/s
    }
    }
}

When the object crosses the threshold of the first sensor, a start time is taken. When the object crosses the threshold of the second sensor, a stop time is taken. You know the distance and calculate the time difference to arrive at velocity.

You might do better using "light beam interrupt".

Please note that you do NOT need to make a thin beam of light to do this, it would actually make it harder to do!

The real trick is to limit the view of a phototransistor or IR detector of a light source than can be a spot on a brightly lit surface or a light bulb spreading many beams of light not needing to be aimed particularly well and available to many detectors. It is the detector that needs to be particular, like down at the bottom of a tube with non-reflective insides.
The detector view needs to be narrow to stop false positives from stray light. If the light source is also thin, they both have to aligned just so which is a real PITA.

Illuminate a wall with IR and many narrow view detectors can be "trip beams".

Out doors.... a box flat black inside shaded from sun can have a bright spot that a narrow-view detector aimed directly at can see even in daytime. It's physics.

1 Like

Code says HCSR04.

How do you keep the sensor for echoPin2 from hearing the echo of the first sensor? How do you keep the first sensor from assuming the pulse from the second sensor is NOT an echo from it's pulse? Are these sensors in different rooms?

The first pulseIn will block until it receives its echo, thus will likely prevent the second pulseIn from detecting the initial rising edge of the echo signal.

Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for the pin to go from LOW to HIGH starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds or gives up and returns 0 if no complete pulse was received within the timeout.

https://docs.arduino.cc/language-reference/en/functions/advanced-io/pulseIn/

why not use one "distance" sensor that is aligned in the direction of movement and knowing the time between measurements, calculate the speed based on the change in distance?

Brilliant idea.

However, the device sends multiple pulses of sound. They are still echoing around somewhere in the air.

It does, but the echo-detection circuitry inside an HC-SR04 sensor is processed into one long, clean, single pulse per trigger:

Since, in the #1 code, both trigger pulses are essentialy simultaneous, then both leading edges of the echo pulses will be simultaneous.

This is a Wokwi sim for a different purpose, but it shows a clean overlap of the echo signals:

A simulation may not reflect reality.

Sure, but the datasheet should represent the behavior of the device.

If you like, cut and paste two datasheet sets of traces, then the first pulseIn should measure length of the HIGH pulse on the first device's "Echo Pulse Output" trace, and the second pulseIn gets to start after the falling edge of end of the first trace, and might well start at while the 2nd "Echo Pulse Output" signal line is still high, and wait for it to return HIGH, or start after the end and wait for apulse that never comes

Draw two sequential pulseIn() durations on these six traces (pins 14 & 32):

HC-SR04 #1 on pins 27 & 14

HC-SR04 #2 on pins 33 & 32

A physical diagram or picure with scales would be a very important.

What is the layout of the sensors and how fast is the object compared to the distance between the sensors? If the object is not in front of the sensor, how far will that sensor read? 400cm? How big is the object? So that at speed, we could tell how long the sensor might be detecting it?

A light interruption idea as per #3 is what is often used. Two beams could get you speed/direction.

Amazon pic of a paired retro-reflective system: