ElectronLab Project Lab
Embedded IoT Arduino Uno Smart Traffic System

Real-Time Car Speed Detection Project with Speed Alarm & LCD Display

Design an intelligent highway speed-trap detection system using an Arduino microcontroller, dual optical infrared sensors, a 16x2 I2C Liquid Crystal Display, and an active buzzer speed limiter warning system.

Reading Time 10 Minutes
Difficulty Level Intermediate
Target Audience Grades 6-12 / Beginners
Hardware Platform Arduino Uno / Nano

1. Aim of the Project

Project Objective

The primary aim of this project is to build an automated real-time vehicle speed measurement system capable of detecting when a car passes across a fixed distance interval, accurately computing its linear velocity in kilometers per hour (km/h) or miles per hour (mph), displaying live metrics on an LCD screen, and sounding an active audio warning alarm if the measured speed exceeds a predefined speed limit threshold.

Traffic monitoring and speed limit enforcement are vital components of modern intelligent transportation systems (ITS). In this practical lab, students learn how professional speed cameras and Doppler laser traps calculate kinematic velocity using time-of-flight (ToF) principles and discrete optical break-beam sensor gates.

2. Interactive 3D Assembly & Circuit Wiring Model

Rotate the 3D model 360 degrees in any direction, zoom in/out with your mouse wheel or gestures, disassemble/explode parts to inspect individual hardware layers, toggle realistic pin-to-pin circuit wires, and click any component to inspect its engineering specifications.

3D Hardware Simulation & Assembly Lab
Left Click + Drag: Rotate Orbit (360°)
Right Click + Drag: Pan Scene
Scroll: Zoom In / Out
Click Component: Inspect Hardware Details
Hovered Component

3. Laboratory Video Masterclass Tutorial

Step-by-step high-definition video walkthrough covering breadboard circuit assembly, sensor threshold alignment, and live radar testing. Enrolled students and instructors can access full video streaming below.

4. Learning Outcomes

By completing this engineering project, students and makers will master the following competencies:

Microsecond Time Tracking

Learn how to capture precise time intervals using the Arduino millis() and micros() hardware timers without blocking system execution.

Optical IR Sensor Interfacing

Understand infrared transmitter-receiver pairs, digital logic state triggers, and optical beam occlusion detection.

I2C Communication Protocol

Connect and program a 16x2 character alphanumeric LCD using only 2 microcontroller data lines (SDA and SCL) via the I2C serial bus.

Kinematic Physics Applied

Convert real-world scale physical distance and elapsed millisecond timestamps into standard speed units (km/h and cm/s).

3. Technologies & Concepts Learned

Embedded C++ (Conditional Flow & State Logic)
I2C Bus Protocol (PCFL8574 Expansion)
Digital Pin Polling (Active LOW vs Active HIGH)
Piezoelectric Sound Generation (PWM Frequencies)
Threshold Alarm System (Speed Limit Logic)
Linear Kinematics (Speed = Distance / Time)

4. Required List of Components

Below is the complete hardware bill of materials (BOM) needed to construct the real-time speed trap circuit:

Component Name Quantity Specification / Purpose Interface Type
Arduino Uno R3 / Nano 1 ATmega328P Microcontroller Core Brain USB / 5V DC
Infrared (IR) Sensor Modules 2 TCRT5000 / LM393 Dual Comparator IR Gates Digital GPIO (Pins D2, D3)
16x2 Character LCD Module 1 Alphanumeric Display for Speed Readouts I2C Bus (Pins A4, A5)
I2C LCD Backpack (PCF8574) 1 Reduces LCD wiring to just 4 wires (Address 0x27) I2C Serial
5V Active Buzzer 1 Audible Over-Speed Violation Alarm Warning Digital GPIO (Pin D4)
5mm Red Indicator LED 1 Visual Over-Speed Warning Indicator Digital GPIO (Pin D5)
220 Ohm Resistor 1 Current limiting protection for indicator LED Passive Through-Hole
Solderless Breadboard & Wires 1 Full-size 830-tie point prototyping board with jumper cables Prototyping

5. Circuit Connections & Pin Mapping

Connect each module to the corresponding Arduino Uno header pins as outlined in the wiring matrix below:

Module Component Module Pin Arduino Uno Pin Connection Description
IR Sensor 1 (Entry Gate) OUT / DO Digital Pin D2 Triggers timestamp when car passes first gate
IR Sensor 1 (Entry Gate) VCC / GND 5V / GND Rail 5V Power Supply
IR Sensor 2 (Exit Gate) OUT / DO Digital Pin D3 Triggers timestamp when car passes second gate
IR Sensor 2 (Exit Gate) VCC / GND 5V / GND Rail 5V Power Supply
16x2 I2C LCD SDA Analog Pin A4 I2C Serial Data line
16x2 I2C LCD SCL Analog Pin A5 I2C Serial Clock line
16x2 I2C LCD VCC / GND 5V / GND Rail 5V Backlight & Logic Power
Active Buzzer Positive (+) Digital Pin D4 Speed violation audio signal
Active Buzzer Negative (-) GND Rail Common Ground
Red Warning LED Anode (+) through 220R Digital Pin D5 Speed violation visual strobe

6. Step-by-Step Assembly Tutorial

1

Position the Distance Speed Trap Gates

Mount the two IR sensor modules facing across the roadway track spaced exactly 10.0 centimeters (0.1 meters) or 20.0 centimeters apart. Use a ruler to ensure precise measurement.

  • Ensure both IR transmitters and receivers are aligned horizontally at the bumper height of your model car.
  • Calibrate the onboard blue potentiometer on both IR modules so the onboard LED turns ON only when an object crosses the beam.
2

Wire the I2C LCD Screen

Connect the 4 pins of your I2C adapter to the Arduino. Connect GND to Arduino GND, VCC to 5V, SDA to Analog Pin A4, and SCL to Analog Pin A5.

  • Turn the small contrast trimpot behind the I2C backpack using a screwdriver until characters appear crisp against the blue backlight.
3

Connect Alarm Output Devices

Insert the active buzzer and red LED into the breadboard. Connect Pin D4 to the buzzer positive terminal and Pin D5 to the 220 Ohm resistor in series with the LED anode.

4

Upload the Arduino Sketch & Run Live Calibration

Connect the Arduino to your computer via USB cable, launch the Arduino IDE, install the LiquidCrystal_I2C library, select your COM port, and upload the sketch below.

7. Complete Arduino Source Code

Here is the fully tested, clean C++ code for the Real-Time Car Speed Detector with audio-visual alarm thresholds:

speed_detection_alarm.ino
/*
 * Project: Real-Time Car Speed Detection & Speed Alarm System
 * Author: ElectronLab STEM Curriculum
 * Target: Arduino Uno / Nano
 * Description: Calculates speed from dual IR beam break timestamps
 */

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Initialize 16x2 LCD with I2C address 0x27 (or 0x3F)
LiquidCrystal_I2C lcd(0x27, 16, 2);

// Hardware Pin Definitions
const int SENSOR_ENTRY_PIN = 2; // IR Sensor 1 (Start Gate)
const int SENSOR_EXIT_PIN  = 3; // IR Sensor 2 (Stop Gate)
const int BUZZER_PIN       = 4; // Active Alert Buzzer
const int ALERT_LED_PIN    = 5; // Red Warning LED

// Physical Configuration (in meters)
const float SENSOR_DISTANCE_METERS = 0.15; // 15 cm distance between sensors
const float SPEED_LIMIT_KMH        = 30.0; // Over-speed alert threshold in km/h

// State variables
unsigned long timeEntry = 0;
unsigned long timeExit  = 0;
bool isCarDetected      = false;

void setup() {
  Serial.begin(9600);
  
  // Configure input sensor pins with internal pullups if required
  pinMode(SENSOR_ENTRY_PIN, INPUT);
  pinMode(SENSOR_EXIT_PIN, INPUT);
  
  // Configure output alarm pins
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(ALERT_LED_PIN, OUTPUT);
  digitalWrite(BUZZER_PIN, LOW);
  digitalWrite(ALERT_LED_PIN, LOW);
  
  // Initialize LCD
  lcd.init();
  lcd.backlight();
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("ElectronLab Radar");
  lcd.setCursor(0, 1);
  lcd.print("Ready for Cars..");
  delay(2000);
  lcd.clear();
  lcd.print("Speed Trap: Active");
}

void loop() {
  // Read digital state from optical sensors (Active LOW when beam occluded)
  int entryState = digitalRead(SENSOR_ENTRY_PIN);
  int exitState  = digitalRead(SENSOR_EXIT_PIN);

  // Step 1: Detect car entering Sensor 1
  if (entryState == LOW && !isCarDetected) {
    timeEntry = millis();
    isCarDetected = true;
    
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Car Detected...");
    lcd.setCursor(0, 1);
    lcd.print("Timing Speed...");
    
    // Wait for the car to clear the first sensor
    while (digitalRead(SENSOR_ENTRY_PIN) == LOW) {
      delay(1);
    }
  }

  // Step 2: Detect car reaching Sensor 2
  if (exitState == LOW && isCarDetected) {
    timeExit = millis();
    isCarDetected = false;
    
    // Calculate elapsed time in seconds
    unsigned long timeElapsedMillis = timeExit - timeEntry;
    
    if (timeElapsedMillis > 10) { // Reject accidental noise
      float timeSeconds = (float)timeElapsedMillis / 1000.0;
      
      // Calculate speed: Speed = Distance (m) / Time (s)
      float speedMps = SENSOR_DISTANCE_METERS / timeSeconds;
      
      // Convert Meters/Sec to Kilometers/Hour (1 m/s = 3.6 km/h)
      float speedKmh = speedMps * 3.6;

      // Print metrics to Serial Monitor
      Serial.print("Elapsed Time (ms): ");
      Serial.print(timeElapsedMillis);
      Serial.print(" | Speed: ");
      Serial.print(speedKmh, 2);
      Serial.println(" km/h");

      // Display metrics on 16x2 LCD
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Speed: ");
      lcd.print(speedKmh, 1);
      lcd.print(" km/h");

      // Step 3: Trigger Speed Alarm if Limit Exceeded
      lcd.setCursor(0, 1);
      if (speedKmh > SPEED_LIMIT_KMH) {
        lcd.print("OVER LIMIT! SLOW");
        triggerSpeedAlarm();
      } else {
        lcd.print("Status: NORMAL");
        delay(3000);
      }
    }
    
    // Reset display for next vehicle
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Speed Trap: Active");
    lcd.setCursor(0, 1);
    lcd.print("Limit: ");
    lcd.print(SPEED_LIMIT_KMH, 0);
    lcd.print(" km/h");
  }
}

// Function to sound buzzer alarm and flash LED
void triggerSpeedAlarm() {
  for (int i = 0; i < 5; i++) {
    digitalWrite(BUZZER_PIN, HIGH);
    digitalWrite(ALERT_LED_PIN, HIGH);
    delay(200);
    digitalWrite(BUZZER_PIN, LOW);
    digitalWrite(ALERT_LED_PIN, LOW);
    delay(200);
  }
}

8. Working Principle & Mathematical Logic

The speed detection algorithm utilizes the fundamental physical definition of linear kinematics:

Velocity (v) = Distance (d) / Elapsed Time (Δt)

Speed in Kilometers per Hour = (Distance in meters / (Time in ms / 1000)) × 3.6

When the moving model vehicle crosses the first infrared sensor gate, the optical beam is occluded, causing the sensor output to transition from HIGH to LOW. The microcontroller registers a timestamp timeEntry = millis().

As the vehicle travels across the known separation span (15 cm = 0.15 m) and occludes the second infrared sensor, the microcontroller registers timeExit = millis(). The system calculates the time difference, computes velocity, checks against the safety limit (30 km/h), and triggers the buzzer alarm when a violation occurs.

9. Testing & Troubleshooting Guide

LCD Screen is Blank / Blue Only

Rotate the blue contrast potentiometer on the back of the I2C adapter with a screwdriver. If characters do not appear, run an I2C scanner sketch to confirm whether your LCD address is 0x27 or 0x3F.

IR Sensor Triggering Continuously

Ambient sunlight contains natural infrared radiation that can false-trigger the receiver. Adjust the onboard potentiometer screw on the IR module counter-clockwise to lower sensitivity.

Negative or Inaccurate Speed Values

Ensure the vehicle passes Sensor 1 (Entry Gate on Pin D2) first before reaching Sensor 2 (Exit Gate on Pin D3). If cars travel in reverse, swap the pin assignments in code.

Buzzer Weak or Not Sounding

Verify that you are using an Active 5V Buzzer (which oscillates automatically with continuous DC current) rather than a passive buzzer which requires a pulsed PWM frequency.