Using Ultrasonic Sensors to check whether an object has crossed the line

I am new to Arduino, and needed some help. I am using an Uno.
What I want to do is try and find out whether an object has crossed into a particular zone using ultrasonic sensors. Basically, we have a model of a car that we want to push past a model of a hospital, showing that the car is in a no-honking zone. I want to place an ultrasonic sensor in front of the hospital such that when the car crosses the sensor, the board recognises that it is in a silence zone.
How do I program the sensor to detect that the car has crossed it?


I’m just working on code for an ultrasonic sensor now (type HC-SR04). The application is slightly different from yours, and I’ve had to put some effort into eliminating false triggering. It stablises itself after 10 seconds, but you can adjust that in the code.
Here is the code if it is of any use to you. It is based on something I found on Sparkfun’s web site but also modified to solve a missing timeout issue with cheap HC-SR04 sensors :


   mod v0.1  20.10.2016  ex. sparkFun  timeouts on waits
   mod v0.2  21.10.2016  add smoothing and alarming

   HC-SR04 Demo
   Demonstration of the HC-SR04 Ultrasonic Sensor
   Date: August 3, 2016

    Connect the ultrasonic sensor to the Arduino as per the
    hardware connections below. Run the sketch and open a serial
    monitor. The distance read from the sensor will be displayed
    in centimeters and inches.

   Hardware Connections:
    Arduino | HC-SR04
      5V    |   VCC
      7     |   Trig
      8     |   Echo
      GND   |   GND

    Public Domain

// Pins
const int TRIG_PIN = 7;
const int ECHO_PIN = 8;
const int BUZZER_PIN = 5;

// Anything over 400 cm (23200 us pulse) is "out of range"
const unsigned int MAX_DIST = 23200;


const int SAMPLE_BUFFER_ENTRIES = 20 ;
unsigned long sample_buffer[ SAMPLE_BUFFER_ENTRIES ] = {0} ;
int sample_buffer_ptr = 0 ;

unsigned long stabilisation_period_start_ms ;
unsigned long alarm_triggered_ms ;
const unsigned long ALARM_DURATION_MS = 4000 ;

// boolean lastValidPulseOutOfAverage = false ;
int consecutiveOutOfAveragePulseCount = 0 ;
const int TRIGGER_LEVEL_OUT_OF_AVERAGE_PULSES = 3 ;  // consecutive

void addSample( unsigned long pulseLengthUs ) {
  sample_buffer[ sample_buffer_ptr ] = pulseLengthUs ;
  sample_buffer_ptr ++ ;
  if ( sample_buffer_ptr >= SAMPLE_BUFFER_ENTRIES ) sample_buffer_ptr = 0 ;

unsigned long averageSampleUs() {
  unsigned long av = 0 ;
  for ( int i = 0 ; i < SAMPLE_BUFFER_ENTRIES ; i ++ ) {
    av += ( sample_buffer[ i ] / SAMPLE_BUFFER_ENTRIES ) ;
  return av ;

void setup() {
  // The Trigger pin will tell the sensor to range find
  pinMode(TRIG_PIN, OUTPUT);
  digitalWrite(TRIG_PIN, LOW);

  // We'll use the serial monitor to view the sensor output

  stabilisation_period_start_ms = millis() ;
  alarm_triggered_ms = 0 ;

void loop() {

  unsigned long t1;
  unsigned long t2;
  unsigned long pulse_width;
  float cm;
  float inches;

  // Alarm

  if ( millis() - alarm_triggered_ms < ALARM_DURATION_MS && alarm_triggered_ms != 0  )  {
    // we are in an alarm
    tone( BUZZER_PIN , 330 , 1000 ) ;

  // Hold the trigger pin high for at least 10 us
  digitalWrite(TRIG_PIN, HIGH);
  digitalWrite(TRIG_PIN, LOW);

  // Wait for pulse on echo pin

  unsigned long wait1 = micros();
  while ( digitalRead(ECHO_PIN) == 0  ) {
    if ( micros() - wait1 > MAX_DIST ) {
      Serial.println("wait1 Out of range");
      return ;

  // Measure how long the echo pin was held high (pulse width)
  // Note: the micros() counter will overflow after ~70 min
  t1 = micros();
  while ( digitalRead(ECHO_PIN) == 1  ) {
    if ( micros() - t1 > MAX_DIST ) {
      Serial.println("wait2 Out of range");
      return ;

  t2 = micros();
  pulse_width = t2 - t1;

  // Calculate distance in centimeters and inches. The constants
  // are found in the datasheet, and calculated from the assumed speed
  //of sound in air at sea level (~340 m/s).
  cm = pulse_width / 58.0;
  inches = pulse_width / 148.0;

  // Print out results
  if ( pulse_width > MAX_DIST ) {
    Serial.println("Out of range");
  } else {

        We have a valid pulse


    if ( millis() - stabilisation_period_start_ms > ( STABILISATION_TIME_SECS * 1000UL ) ) {
      unsigned long avPulse = averageSampleUs() ;
      if ( labs ( avPulse - pulse_width ) >  avPulse / 7  ) {
        // circa 15% change
        if ( consecutiveOutOfAveragePulseCount >=  TRIGGER_LEVEL_OUT_OF_AVERAGE_PULSES  ) {
          // initiate alarm and reset
          Serial.println("alarm triggered");
          alarm_triggered_ms = millis() ;
          consecutiveOutOfAveragePulseCount = 0 ;
          stabilisation_period_start_ms = millis() ;
        else {
          consecutiveOutOfAveragePulseCount ++ ;
          Serial.println("got out of average pulse. Dropping");
      else {
        addSample( pulse_width ) ;
        consecutiveOutOfAveragePulseCount = 0  ;
    else {
      Serial.println("in Stabilisation Period");
      addSample( pulse_width ) ;
      consecutiveOutOfAveragePulseCount = 0 ;


    Serial.print(" cm \t");
    Serial.println(" in");

  // Wait at least 60ms before next measurement

Thank you so much! I do have a few queries though. As I mentioned, I am completely new to programming - I have done a few basics so far and am still learning.
From what I understand, the only way to find out if there is an obstacle crossing the ultrasound sensor I to measure a distance and set a threshold so if the distance is less than the threshold, it implies that there is an obstacle. Is that right?
Also, is there any website that offers online Arduino programming classes? Somewhere I can learn all the concepts required to code properly, and understand all the statement. The Arduino playground seems a bit complicated to me.

I also thought of this - Would it be possible to check if an object has crossed the sensors by using two ultrasonic sensors opposite each other? Then we could use one sensor to transmit a beam and the other to receive it. If the sensor stops receiving, it would imply that something is blocking the beam and this could be considered as the car crossing the line - almost like the photoelectric sensors they use in smoke detectors. Would this work?

The code I supplied works like this. It is intended as an alarm system but should be appropriate for your application.

You point the ultrasonic sensor at something. In your case, the road outside the model hospital. It stabilises on this scene and remembers the distance to the road. If something comes along (a model car) then it notices the distance has changed and issues an alarm. If the car is stationary, it again stabilises. Once the car leaves, it raises an alarm again and once again stabilises.

There are other technologies for achieving the same thing:
Beam break (say Infra red)
magnet and hall effect transistor
pressure pad.

One good way to start is with the Arduino starter kit. You learn the basics of hardware and software in parallel as you follow through the example projects.

Thank you! Will try it out and let you know how it goes!

I want to place an ultrasonic sensor in front of the hospital such that when the car crosses the sensor, the board recognises that it is in a silence zone.

That is not going to happen. An ultrasonic sensor will tell you how far away the nearest object is, but NOT what the object is nor the direction to the object.

Now, you could use it to tell you if there is something near the car, if the sensor is connected to the car, but then you wouldn't be able to tell is that something was a hospital or another car or the back wall of your garage.

If the sensor is connected to the hospital, it could tell that there is something, be that a car, a truck, or a pedestrian, nearby, but how you would tell that thing that it was in a no honking zone, I do not know. Nor do I have any idea what good that would do. How often do people park in no parking zones? What makes you think that they won't honk in a no honking zone?