Skip to content

G17: Smart Red Light Violation Detection System

yousefsebaie edited this page May 20, 2026 · 14 revisions

G17: Smart Red Light Violation Detection System

Name GitHub
Yousef Sayed GH_UID1
Marwan Abudaif GH_UID2
Hadi Hesham GH_UID3

Github Repo: https://github.com/MarwanMoh11/smart-redlight-tm4c123

1. The Proposal

Abstract / Elevator Pitch

Running red lights is a leading cause of serious traffic accidents in Egypt and worldwide. Traffic officers cannot manually monitor every intersection around the clock, and without automated evidence capture, authorities have no reliable way to issue fines or deter repeat offenders. Simple motion-based detection systems cannot distinguish between a pedestrian crossing the street and a vehicle running a red light, producing false alarms that waste enforcement resources.

Our project is the Smart Red Light Violation Detection System — an embedded real-time system that automatically detects vehicles crossing a stop line during a red light phase, captures photographic evidence, and logs every violation with a timestamp to a PC. The system detects a vehicle at the stop line, and only acts when the light is red. To distinguish a real vehicle from a pedestrian, a software filter measures how long an object lingers at the sensor: very brief passes are treated as pedestrians or noise and ignored, while a sustained pass within a calibrated time window is treated as a vehicle.

The firmware runs on a TI Tiva C TM4C123GXL Launchpad using FreeRTOS with six concurrent tasks: sensor detection, violation logic, traffic light cycle, alert, camera capture, and UART logging. When a violation is confirmed during the red light phase, the violation event fans out to three independent handlers in parallel: an alert handler that flashes a visual warning, a camera handler that triggers a photo capture, and a logging handler that writes a timestamped record to a PC terminal. This system demonstrates a practical, real-world embedded application of multitasking, inter-task communication through queues, priority scheduling, and event-driven sensor handling using low-cost hardware.

Project Objectives & Scope

Minimum Viable Product (MVP)

  • Automatic traffic light cycle: GREEN → YELLOW → RED
  • Detection active only during the RED light phase
  • Vehicle detection at the stop line
  • Software pedestrian filtering using a dwell-time window
  • Full FreeRTOS architecture with 6 concurrent tasks
  • Proper inter-task communication using queues, priorities, timers, and shared state
  • Fan-out dispatch: each violation triggers alert, camera, and log handlers in parallel
  • Visual alert on confirmed violation
  • Photo capture of the violating vehicle
  • UART event logging to PC terminal with timestamps

Stretch Goals

  • Replace ultrasonic sensor with dual Force-Sensitive Resistors (FSRs) for axle-based detection
  • Hardware-level pedestrian filtering using ADC threshold tuning
  • Flash LED synchronized with camera capture
  • 16x2 LCD display showing current light state and violation count
  • Audible buzzer alert on confirmed violation
  • Manual override buttons: force red light and reset counter
  • Persistent violation count stored in flash memory
  • Emergency vehicle exemption mode
  • Multi-lane support by replicating the hardware unit per lane

2. System Architecture

2.1 High-Level Block Diagram

System Architecture Block Diagram

2.2 Subsystem Breakdown

Subsystem Description
Sensor subsystem HC-SR04 ultrasonic sensor connected to PB0 as TRIG and PB1 as ECHO. It is polled at 50 Hz. A software dwell-time filter eliminates pedestrians and stationary objects. The subsystem is designed so the ultrasonic sensor can later be replaced by dual FSR pads without changing the downstream tasks.
Traffic light subsystem LightTask drives the onboard RGB LED: GREEN on PF3, YELLOW on PF1 + PF3, and RED on PF1. The light states are controlled by timed delays. A shared volatile variable g_current_light carries the current state to ViolationTask.
Violation logic subsystem ViolationTask receives sensor events, checks whether the current light is red, builds a violation_record_t, and sends it to the alert, camera, and log queues. It is fully decoupled from GPIO and UART.
Alert subsystem AlertTask receives violation records and produces a visual flicker on the RGB LED for 500 ms using 50 ms burst intervals. Flash LED and buzzer hooks are prepared in alert_task.c.
Camera subsystem CameraTask receives violation records and triggers photo capture of the violating vehicle. The original ESP32-CAM was replaced with a laptop webcam after firmware issues.
Logging subsystem LogTask receives violation records and writes timestamped messages to UART0 at 115200 baud. The logs can be viewed on the PC using picocom.

3. Hardware Design

3.1 Component Selection

Component Purpose Notes
TI Tiva C TM4C123GXL Launchpad Main MCU ARM Cortex-M4F, 80 MHz, 256 KB Flash, 32 KB SRAM. Runs FreeRTOS and all six tasks.
HC-SR04 Ultrasonic Sensor Vehicle proximity detection Current working sensor. TRIG connected to PB0 and ECHO connected to PB1.
2x Force-Sensitive Resistors (FSR 402) Planned final vehicle detection Intended for front and rear axle detection. Planned connection to ADC channels PE2 and PE3.
Laptop Webcam Photograph capture Replaced ESP32-CAM after firmware failure.
Onboard RGB LED Traffic light simulation and violation alert PF1 for red, PF3 for green, PF1 + PF3 for yellow.
1W Flash LED + NPN transistor Optional camera flash Planned to be driven from PE2 for a 20 ms burst.
Active Buzzer Optional audible alert Planned to be driven from PE1.
Breadboard + jumper wires Prototyping Used for wiring and testing.

3.2 Schematics & Wiring

HC-SR04 to TM4C123GXL

HC-SR04 Pin Tiva Silkscreen Port/Pin
VCC +3.3V
TRIG PB0 GPIO_PORTB_BASE, GPIO_PIN_0
ECHO PB1 GPIO_PORTB_BASE, GPIO_PIN_1
GND GND

Important: The HC-SR04 was powered from 3.3V instead of 5V so that the ECHO signal remains safe for PB1.

Onboard RGB LED

Color Pin FreeRTOS State
Red PF1 LIGHT_RED
Blue PF2 Unused in the traffic cycle
Green PF3 LIGHT_GREEN
Yellow PF1 + PF3 LIGHT_YELLOW

Alert & Camera Outputs

Signal Port/Pin Purpose
Flash LED PE2 Optional 20 ms burst on violation
Buzzer PE1 Optional 500 ms alert on violation
Camera trigger Laptop webcam Captures image on violation event
Debug UART TX PA1 / U0TX UART logging at 115200 baud

Manual Override Buttons

Button Pin Function
SW1 PF4 Force RED phase
SW2 PF0 Reset violation counter

3.3 Bill of Materials

Component Qty Estimated Cost
TI Tiva C TM4C123GXL Launchpad 1 ~120 EGP
HC-SR04 Ultrasonic Sensor 1 ~15 EGP
Force-Sensitive Resistors 2 ~30 EGP
1W LED + NPN transistor 1 set ~10 EGP
Active Buzzer 1 ~5 EGP
Laptop Webcam 1 Existing / reused
Breadboard + jumper wires 1 set ~20 EGP
Total ~200 EGP

3.4 Power Budget

Component Supply Typical Current Peak Current
TM4C123GXL MCU 3.3V 30 mA 50 mA
HC-SR04 3.3V 15 mA 15 mA
Onboard RGB LED 3.3V 3 mA 3 mA
1W Flash LED 5V 300 mA
Active Buzzer 5V 30 mA 30 mA
3.3V rail total ~48 mA ~68 mA
5V rail total ~30 mA ~330 mA

The Launchpad onboard LDO supplies enough current for the MCU, sensor, and onboard LED. The optional buzzer and flash LED use the USB-supplied 5V rail. The laptop webcam is powered by the host PC and does not draw power from the Launchpad.

4. Software Implementation

4.1 Software Architecture

The firmware is implemented as a FreeRTOS preemptive multitasking application targeting the TM4C123GXL at 80 MHz. The clock is configured using SysCtlClockSet with the PLL from a 16 MHz crystal. The kernel tick rate is 1 ms using configTICK_RATE_HZ = 1000, which gives 1 ms resolution for delays and timestamps. Heap management uses heap_4 with a 20 KB heap.

Six tasks are created in main() before calling vTaskStartScheduler().

Task Stack Priority Responsibility
SensorTask 512 words 4 Poll HC-SR04 at 50 Hz, apply dwell-time filtering, and post SENSOR_VEHICLE_DETECTED to xSensorEventQueue.
ViolationTask 256 words 3 Block on the sensor queue, check whether the light is red, build a violation record, and fan out the event to three queues.
AlertTask 256 words 3 Block on xAlertQueue and produce a visual flicker.
LightTask 256 words 2 Cycle GREEN → YELLOW → RED and update g_current_light.
CameraTask 256 words 2 Block on xCameraQueue and trigger photo capture.
LogTask 512 words 1 Block on xLogQueue and write timestamped violation records to UART0.

4.2 Inter-Task Communication

Queue Item Type Depth Producer → Consumer
xSensorEventQueue sensor_event_t 8 SensorTask → ViolationTask
xAlertQueue violation_record_t 4 ViolationTask → AlertTask
xCameraQueue violation_record_t 4 ViolationTask → CameraTask
xLogQueue violation_record_t 16 ViolationTask → LogTask

g_current_light is a volatile light_state_t. It has one writer, LightTask, and one reader, ViolationTask. No mutex is required because the read/write operation is atomic on a 32-bit MCU.

4.3 Flowcharts & State Machines

Overall System Data Flow

flowchart LR
    A[HC-SR04 Sensor] -->|distance reading| B[SensorTask]
    B -->|SENSOR_VEHICLE_DETECTED| C[ViolationTask]
    L[LightTask] -->|g_current_light| C
    C -->|if RED| D[AlertTask]
    C -->|if RED| E[CameraTask]
    C -->|if RED| F[LogTask]
    D -->|visual flicker| G[RGB LED]
    E -->|capture request| H[Laptop Webcam]
    F -->|UART 115200 baud| I[PC Terminal]
    L -->|traffic light state| G
Loading

Traffic Light State Machine

stateDiagram-v2
    [*] --> GREEN
    GREEN --> YELLOW: after 6000 ms
    YELLOW --> RED: after 2000 ms
    RED --> GREEN: after 5000 ms
Loading

Sensor Pedestrian Filter State Machine

stateDiagram-v2
    [*] --> S_IDLE
    S_IDLE --> S_PRESENT: object detected below 30 cm
    S_PRESENT --> S_IDLE: object remains longer than 2000 ms
    S_PRESENT --> CHECK: object leaves
    CHECK --> S_IDLE: dwell time below 150 ms
    CHECK --> EVENT: dwell time between 150 and 2000 ms
    EVENT --> S_IDLE: post vehicle event
Loading

Violation Logic Flow

flowchart TD
    A[Wait for sensor event] --> B{Vehicle detected?}
    B -->|No| A
    B -->|Yes| C{Is light RED?}
    C -->|No| D[Discard as legal pass]
    D --> A
    C -->|Yes| E[Build violation_record_t]
    E --> F[Send to Alert Queue]
    E --> G[Send to Camera Queue]
    E --> H[Send to Log Queue]
    F --> A
    G --> A
    H --> A
Loading

4.4 Key Algorithms

HC-SR04 Distance Measurement

The HC-SR04 is triggered by sending a 10 microsecond HIGH pulse on PB0. The firmware then waits for the ECHO signal on PB1. The pulse width is measured and converted to distance using:

distance_cm = pulse_us / 58;

Readings of 0 cm or more than 400 cm are treated as out-of-range and represented as 0xFFFF.

Dwell-Time Pedestrian Filter

The system uses a dwell-time filter to reduce false detections.

  • If the distance reading is below 30 cm, the system enters S_PRESENT.
  • The entry tick is saved using the FreeRTOS tick counter.
  • When the object leaves, the dwell time is calculated:
dwell_ms = (now - entered_tick) * portTICK_PERIOD_MS;
  • If dwell time is less than 150 ms, the object is treated as a pedestrian, noise, or very quick pass.
  • If dwell time is greater than 2000 ms, the object is treated as stationary and ignored.
  • If dwell time is between 150 ms and 2000 ms, the object is treated as a valid vehicle event.

Fan-Out Dispatch

ViolationTask uses zero-timeout xQueueSend() calls. This prevents the dispatcher from blocking if one downstream queue is full. This design ensures that a slow consumer task does not delay the alert, camera, or logging path.

5. Development Environment

Tool Details
Toolchain gcc-arm-none-eabi
Linker/Assembler binutils-arm-none-eabi
C Library libnewlib-arm-none-eabi
Build system GNU Make
FreeRTOS Kernel V11.1.0
TivaWare DriverLib SW-TM4C-2.2.0.295
Flasher lm4flash
Serial monitor picocom -b 115200 /dev/ttyACM0
OS Ubuntu 22.04 / Linux Mint 21
IDE Text editor + terminal

Build and Flash Commands

git clone https://github.com/MarwanMoh11/smart-redlight-tm4c123.git
cd smart-redlight-tm4c123
make
make flash
picocom -b 115200 /dev/ttyACM0

Example Successful Build Output

   text    data     bss     dec     hex filename
  11000       8   21800   32808    8028 build/redlight.elf

6. Testing, Validation & Debugging

6.1 Unit Testing

Module Test Method Pass Criterion
HCSR04_ReadCm() Held object at known distances such as 10 cm, 20 cm, and 30 cm, then read UART output. Reading within ±2 cm of ruler measurement.
Dwell-time filter Waved hand at different speeds. No events for swipes below 150 ms or held hand above 2 seconds.
LightTask timing Measured phase durations using UART phase-start markers. GREEN about 6 seconds, YELLOW about 2 seconds, RED about 5 seconds.
ViolationTask dispatch Injected SENSOR_VEHICLE_DETECTED while forcing RED state. Alert, camera, and log handlers fire within the same scheduler cycle.
LogTask output Checked UART format and incrementing counter. Correct violation message printed with number and tick timestamp.

6.2 Integration Testing

Phase Action Expected Result
GREEN Wave hand at sensor for 200–800 ms. No violation. Legal pass is ignored.
YELLOW Wave hand at sensor. No violation. Legal pass is ignored.
RED Quick swipe below 150 ms. No violation. Pedestrian filter rejects the event.
RED Hold hand still for more than 2000 ms. No violation. Stationary filter rejects the event.
RED Normal pass between 200 and 1500 ms. Violation confirmed: RGB flicker, UART log, and camera capture.
RED repeated Two back-to-back passes. Two separate records are generated and counter increments correctly.

6.3 UART Output for a Successful Violation

=== Smart Red Light System Online ===
Wave hand at sensor during RED phase to trigger violation.

--- GREEN ---
--- YELLOW ---
--- RED (detection active) ---
>>> VIOLATION #1 at tick=12345 (light=RED)
    [CAMERA] capture_request tick=12345 -> img_12345.jpg
--- GREEN ---

6.4 Challenges & Solutions

Challenge Root Cause Solution
Boot loop or banner repeating Stack overflow in SensorTask. Increased SensorTask stack from 256 to 512 words.
LED stuck on GREEN SensorTask was busy-polling without yielding, starving LightTask. Moved sensor polling to 50 Hz using vTaskDelay.
Double violation events Sensor task was re-posting before ViolationTask drained the queue. Added S_PRESENT state guard.
UART garbled output More than one task attempted to write to UART. Logging was isolated through LogTask.
HC-SR04 always reads 0 cm TRIG and ECHO pins were swapped on the breadboard. Verified wiring against silkscreen and added a startup pin-configuration message.
ESP32-CAM unusable ESP32-CAM firmware became unreliable and would no longer flash or boot consistently. Replaced ESP32-CAM with a laptop webcam while keeping the same camera-task interface.
FSR pressure sensors delayed Sensors did not arrive in time for the working build. Used HC-SR04 as a stand-in sensor. The modular design allows later replacement by editing only the sensor module.
make flash permission denied User did not have serial-device permissions. Added user to dialout and plugdev, installed udev rules, and logged in again.

7. Results & Demonstration

7.1 Final Prototype

The current build runs fully on the TM4C123GXL Launchpad with the HC-SR04 connected to PB0 and PB1. The onboard RGB LED acts as both the traffic light and the violation alert. All six FreeRTOS tasks are active and communicate through queues. Photo capture is handled by a laptop webcam triggered on each violation event, and UART output is viewed in real time through picocom at 115200 baud.

Photos of the completed breadboard setup should be added after the final demo build.

7.2 Video Demonstration

Demo video link should be added before the final presentation.

7.3 Performance Metrics

Metric Target Measured
Sensor poll rate 50 Hz / 20 ms period 50 Hz verified by UART timing
Traffic light phase accuracy ±100 ms ±50 ms
Violation detection latency Less than 100 ms after object departure About 20 ms
Pedestrian false positive rate 0% for passes below 150 ms 0% across 20 test swipes
Stationary false positive rate 0% for objects held above 2000 ms 0% across 10 held-hand tests
Missed violations 0% for 200–1500 ms passes 0%, 10 out of 10 detected
UART log latency Less than one scheduler cycle Less than 2 ms

8. Project Management

8.1 Division of Labor

Team Member Primary Responsibilities
Yousef Sayed Hardware wiring, sensor interfacing, sensor task implementation, pedestrian-filter firmware, violation logic, and threshold calibration.
Marwan Abudaif Camera integration, alert/flash circuit, traffic light task, timing cycle, system integration, and build system.
Hadi Hesham UART logging task, PC terminal protocol, alert task, wiki documentation, proposal, final presentation, and integration testing.

All team members collaborated on:

  • System integration and debugging
  • Edge-case testing
  • Pedestrian filter validation
  • Partial-crossing and timeout handling
  • Demo preparation and rehearsal
  • Final presentation delivery

8.2 Timeline

Date Milestone Status
Apr 15 Proposal presentation Complete
Apr 20 Wiki page live / Checkpoint A Complete
Apr 20 – Apr 28 Core firmware: sensor reading, traffic light cycle, and state machine Complete
Apr 29 Progress demo: live violation detection working Complete
Apr 30 – May 5 Full integration: camera capture, alert, and UART logging Complete
May 6 Integration update / Checkpoint B Complete
May 7 – May 12 Bug fixes, threshold tuning, edge-case testing, and demo rehearsal In progress
May 13 Final demo and presentation Pending

9. Appendices & References

9.1 Source Code Repository

https://github.com/MarwanMoh11/smart-redlight-tm4c123

9.2 References

  1. Texas Instruments, TM4C123GH6PM Datasheet, SPMS376E.
    https://www.ti.com/product/TM4C123GH6PM

  2. Texas Instruments, TivaWare Peripheral Driver Library User's Guide, SPMU298D.

  3. FreeRTOS, FreeRTOS Documentation and Reference Manual.
    https://www.freertos.org/Documentation/RTOS_book.html

  4. Elec Freaks, HC-SR04 Ultrasonic Sensor Datasheet.

  5. Interlink Electronics, FSR 402 Integration Guide.
    https://www.interlinkelectronics.com/fsr-402

  6. Richard Barry, Mastering the FreeRTOS Real Time Kernel.

  7. CSCE 4301 Course Materials, Embedded Systems, Spring 2026, AUC.

Clone this wiki locally