-
Notifications
You must be signed in to change notification settings - Fork 4
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
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 (ARM Cortex-M4F at 80 MHz) using FreeRTOS with six concurrent tasks (sensor detection, violation logic, traffic light cycle, alert, camera capture, UART logging) across multiple priority levels. 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 via queues, priority scheduling, and event-driven sensor handling — all using low-cost hardware readily available in Egypt.
Minimum Viable Product (MVP):
- Automatic traffic light cycle (GREEN → YELLOW → RED) using software timers
- Detection active only during the RED light phase
- Vehicle detection at the stop line
- Software pedestrian filtering via a dwell-time window
- Full FreeRTOS architecture with 6 concurrent tasks and proper inter-task communication (queues, priority scheduling, software timers, 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 via 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, reset counter)
- Persistent violation count stored in flash memory (survives power cuts)
- Emergency vehicle exemption mode
- Multi-lane support by replicating the hardware unit per lane
| Subsystem | Description |
|---|---|
| Sensor subsystem | HC-SR04 ultrasonic sensor (PB0 = TRIG, PB1 = ECHO) polled at 50 Hz. A software dwell-time filter eliminates pedestrians (<150 ms) and stationary objects (>2000 ms). Designed to be replaced by dual FSR pads on ADC channels PE2/PE3 with no changes to downstream tasks. |
| Traffic light subsystem | LightTask drives the onboard RGB LED: GREEN (PF3), YELLOW (PF1+PF3), RED (PF1). Phase durations are software-timer driven. A shared volatile g_current_light variable carries state to ViolationTask. |
| Violation logic subsystem | ViolationTask is a pure dispatcher. It blocks on the sensor event queue, checks g_current_light == LIGHT_RED, builds a violation_record_t, and fans it out to three downstream queues with zero-timeout sends. No GPIO, no UART — fully decoupled and unit-testable. |
| Alert subsystem | AlertTask receives violation records and produces a visual flicker on the RGB LED (500 ms at 50 ms burst intervals). Flash LED and buzzer hooks are wired and ready in alert_task.c. |
| Camera subsystem | CameraTask receives violation records and triggers a photo capture of the violating vehicle. The original ESP32-CAM was replaced with a laptop webcam after a firmware failure (see Challenges). |
| Logging subsystem | LogTask receives violation records and writes a timestamped line (>>> VIOLATION #N at tick=T) to UART0 (115200 baud), viewable with picocom on the PC. |
| Component | Purpose | Notes |
|---|---|---|
| TI Tiva C TM4C123GXL Launchpad | Main MCU (ARM Cortex-M4F, 80 MHz, 256 KB Flash, 32 KB SRAM) | Runs FreeRTOS + all 6 tasks |
| HC-SR04 Ultrasonic Sensor | Vehicle proximity detection (current build) | 3.3 V powered; TRIG → PB0, ECHO → PB1 |
| 2x Force-Sensitive Resistors (FSR 402) | Planned final vehicle detection (front + rear axle) | To be wired to ADC channels PE2/PE3 |
| Laptop Webcam | Photograph capture of violating vehicle | Replaced the ESP32-CAM after firmware burnout |
| Onboard RGB LED | Traffic light simulation + violation flicker | PF1 (red), PF3 (green), PF1+PF3 (yellow) |
| 1W Flash LED + NPN transistor (BC547) | Camera flash synchronized to capture (optional) | Driven from PE2; 20 ms burst |
| Active Buzzer (5V) | Audible violation alert (optional) | Driven from PE1 |
| Breadboard + jumper wires | Prototyping connections | — |
HC-SR04 to TM4C123GXL
| HC-SR04 Pin | Tiva Silkscreen | Port/Pin |
|---|---|---|
| VCC | +3.3V | — |
| TRIG | PB0 | GPIO_PORTB_BASE, GPIO_PIN_0 (output) |
| ECHO | PB1 | GPIO_PORTB_BASE, GPIO_PIN_1 (input, pull-down) |
| GND | GND | — |
Important: Power the HC-SR04 from 3.3V, not 5V. The ECHO line stays within PB1's safe input range.
Onboard RGB LED (Traffic Light)
| Color | Pin | FreeRTOS State |
|---|---|---|
| Red | PF1 | LIGHT_RED |
| Blue | PF2 | (unused in traffic cycle) |
| Green | PF3 | LIGHT_GREEN |
| Yellow | PF1 + PF3 | LIGHT_YELLOW |
Alert & Camera Outputs
| Signal | Port/Pin | Purpose |
|---|---|---|
| Flash LED | PE2 | 20 ms burst on violation (optional) |
| Buzzer | PE1 | 500 ms alert on violation (optional) |
| Camera trigger | Laptop webcam (host-side) | Captures image on violation event |
| Debug UART TX | PA1 (U0TX) | 115200 baud log to PC |
Manual Override Buttons (onboard)
| Button | Pin | Function |
|---|---|---|
| SW1 | PF4 | Force RED phase |
| SW2 | PF0 | Reset violation counter |
| Component | Qty | Estimated Cost (EGP) |
|---|---|---|
| TI Tiva C TM4C123GXL Launchpad | 1 | ~120 |
| HC-SR04 Ultrasonic Sensor | 1 | ~15 |
| Force-Sensitive Resistors (FSR 402) | 2 | ~30 |
| 1W LED + NPN transistor (BC547) | 1 set | ~10 |
| Active Buzzer (5V) | 1 | ~5 |
| Laptop Webcam | 1 | (existing / reused) |
| Breadboard + jumper wires | 1 set | ~20 |
| Total | ~200 EGP |
| Component | Supply | Typ. Current | Peak Current |
|---|---|---|---|
| TM4C123GXL (MCU at 80 MHz) | 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 (via transistor) | 5V | — | 300 mA (20 ms burst) |
| Active Buzzer | 5V | 30 mA | 30 mA |
| 3.3V rail total | ~48 mA | ~68 mA | |
| 5V rail total | ~30 mA | ~330 mA |
The Launchpad's onboard LDO supplies up to 250 mA on the 3.3V rail, comfortably covering the MCU, sensor, and LED. The 5V rail (sourced from USB) handles the optional buzzer and flash LED burst. The camera runs on the host laptop and draws no power from the board.
The firmware is structured as a FreeRTOS preemptive multitasking application targeting the TM4C123GXL at 80 MHz (configured via SysCtlClockSet with PLL from a 16 MHz crystal). The kernel tick rate is 1 ms (configTICK_RATE_HZ = 1000), giving 1 ms resolution for all delays and timestamps. Heap management uses heap_4 with a 20 KB heap.
Six tasks are created in main() before vTaskStartScheduler() is called:
| Task | Stack (words) | Priority | Responsibility |
|---|---|---|---|
| SensorTask | 512 | 4 (highest) | Poll HC-SR04 at 50 Hz; apply dwell-time pedestrian filter; post SENSOR_VEHICLE_DETECTED to xSensorEventQueue |
| ViolationTask | 256 | 3 | Block on xSensorEventQueue; if g_current_light == LIGHT_RED, build violation_record_t and fan-out to three queues |
| AlertTask | 256 | 3 | Block on xAlertQueue; produce visual flicker (flash LED + buzzer hooks ready) |
| LightTask | 256 | 2 | Cycle GREEN→YELLOW→RED using vTaskDelay; update volatile g_current_light |
| CameraTask | 256 | 2 | Block on xCameraQueue; trigger laptop webcam capture |
| LogTask | 512 | 1 (lowest) | Block on xLogQueue; write timestamped violation record to UART0 |
Inter-task communication:
| Queue | Item Type | Depth | Producer → Consumer |
|---|---|---|---|
| xSensorEventQueue | sensor_event_t (uint8 enum) | 8 | SensorTask → ViolationTask |
| xAlertQueue | violation_record_t (12 bytes) | 4 | ViolationTask → AlertTask |
| xCameraQueue | violation_record_t (12 bytes) | 4 | ViolationTask → CameraTask |
| xLogQueue | violation_record_t (12 bytes) | 16 | ViolationTask → LogTask |
g_current_light is a volatile light_state_t — single-writer (LightTask), single-reader (ViolationTask). No mutex required; the read is atomic on a 32-bit MCU.
Overall System Data Flow
Readings of 0 or >400 cm are treated as out-of-range (0xFFFF).
**Dwell-Time Pedestrian Filter**
- A reading of `cm < 30` transitions S_IDLE to S_PRESENT, recording the entry tick.
- When the object leaves: `dwell_ms = (now - entered) × portTICK_PERIOD_MS`
- Only dwell times in [150 ms, 2000 ms] produce a sensor event. Shorter = pedestrian/noise; longer = stationary object.
When FSR hardware is integrated, this is replaced by a dual-threshold ADC check: ADC count > `FSR_ADC_THRESHOLD` on both sensors within a [50 ms, 500 ms] axle-gap window.
**Fan-Out Dispatch**
ViolationTask uses zero-timeout `xQueueSend` calls so it never blocks on a slow consumer. If a downstream queue is full, that record is silently dropped — preventing a stalled AlertTask from delaying camera capture or logging.
## 4.4 Development Environment:
| Tool | Details |
|---|---|
| Toolchain | gcc-arm-none-eabi (Ubuntu package) |
| Linker/Assembler | binutils-arm-none-eabi |
| C Library | libnewlib-arm-none-eabi |
| Build system | GNU Make (Makefile in repo root) |
| FreeRTOS Kernel | V11.1.0 (FreeRTOS/FreeRTOS-Kernel) |
| TivaWare DriverLib | SW-TM4C-2.2.0.295 (TI, free download) |
| Flasher | lm4flash (utzig/lm4tools) |
| Serial monitor | picocom -b 115200 /dev/ttyACM0 |
| OS | Ubuntu 22.04 / Linux Mint 21 |
| IDE | None required — text editor + terminal |
Build and flash:
Successful build output:
# 5. Testing, Validation & Debugging
## 5.1 Unit Testing:
| Module | Test Method | Pass Criterion |
|---|---|---|
| HCSR04_ReadCm() | Held object at known distances (10, 20, 30 cm), read UART output | Reading within ±2 cm of ruler measurement |
| Dwell-time filter | Waved hand at various speeds | No events for swipes <150 ms or held hand >2 s |
| LightTask timing | Measured phase durations via UART phase-start markers | GREEN ~6.0 s, YELLOW ~2.0 s, RED ~5.0 s (±50 ms) |
| ViolationTask dispatch | Manually injected SENSOR_VEHICLE_DETECTED while forcing RED state | Alert, camera, and log all fire within same scheduler cycle |
| LogTask output | Checked UART format and incrementing counter | ">>> VIOLATION #N at tick=T (light=RED)" printed correctly |
## 5.2 Integration Testing:
| Phase | Action | Expected Result |
|---|---|---|
| GREEN | Wave hand at sensor (200–800 ms) | No violation — legal pass silently ignored |
| YELLOW | Wave hand at sensor | No violation — legal pass |
| RED | Quick swipe (<150 ms) | No violation — pedestrian filter active |
| RED | Hold hand still (>2000 ms) | No violation — stationary filter active |
| RED | Normal pass (200–1500 ms) | VIOLATION: red flicker 500 ms + UART log + camera capture |
| RED (repeated) | Two back-to-back passes | Two separate records, counter increments correctly |
UART output for a successful violation:
## 5.3 Challenges & Solutions:
| Challenge | Root Cause | Solution |
|---|---|---|
| Boot loop / banner repeating | Stack overflow in SensorTask | Increased SensorTask stack from 256 to 512 words |
| LED stuck on GREEN | SensorTask busy-polling without yielding, starving LightTask | Moved to 50 Hz polling with vTaskDelay |
| Double violation events | Sensor task re-posting before ViolationTask drained queue | Added S_PRESENT state guard |
| UART garbled output | CameraTask + LogTask both calling UARTCharPut concurrently | Serialized via priority: CameraTask=2, LogTask=1 |
| HC-SR04 always reads 0 cm | TRIG and ECHO pins swapped on breadboard | Verified against silkscreen; added startup pin-config message |
| ESP32-CAM unusable | The ESP32-CAM firmware entered a burnout cycle and would no longer flash or boot reliably | Replaced the ESP32-CAM with a laptop webcam for photo capture; the CameraTask interface is unchanged, so the rest of the system was unaffected |
| FSR pressure sensors delayed | Sensors did not arrive in time for the working build | Used the HC-SR04 ultrasonic sensor as a stand-in; the modular design means only sensor_task.c changes when the FSRs are integrated |
| make flash permission denied | User not in dialout group | sudo usermod -aG dialout,plugdev $USER + udev rules + re-login |
# 6. Results & Demonstration
## 6.1 Final Prototype:
The current build runs fully on the TM4C123GXL Launchpad with the HC-SR04 wired to PB0/PB1. The onboard RGB LED serves as the traffic light and the violation alert. All 6 FreeRTOS tasks are active and communicating via queues. Photo capture is handled by a laptop webcam triggered on each violation event, and UART output is viewable in real time via picocom at 115200 baud.
*Photos of the completed breadboard setup to be added after the final demo build.*
## 6.2 Video Demonstration:
*Link to demo video to be added before the May 13 final presentation.*
## 6.3 Performance Metrics:
| Metric | Target | Measured |
|---|---|---|
| Sensor poll rate | 50 Hz (20 ms period) | 50 Hz (verified via UART timing) |
| Traffic light phase accuracy | ±100 ms | ±50 ms (FreeRTOS tick = 1 ms) |
| Violation detection latency | < 100 ms from object departure | ~20 ms (one poll cycle + queue send) |
| Pedestrian false positive rate | 0% for <150 ms passes | 0% (validated across 20 test swipes) |
| Stationary false positive rate | 0% for >2000 ms objects | 0% (validated across 10 held-hand tests) |
| Missed violations | 0% for 200–1500 ms passes | 0% (10/10 detected in RED phase) |
| UART log latency | < 1 scheduler cycle | < 2 ms (LogTask at priority 1) |
# 7. Project Management
## 7.1 Division of Labor:
| Team Member | Primary Responsibilities |
| ------------- | ------------- |
| **Yousef Sayed** | Hardware wiring, sensor interfacing, sensor task and pedestrian-filter firmware, violation logic, threshold calibration |
| **Marwan Abudaif** | Camera integration, alert/flash circuit, traffic light task and timing cycle, system integration, build system |
| **Hadi Hesham** | UART logging task and PC terminal protocol, alert task, wiki documentation, proposal and final presentation, integration testing |
All team members collaborated on:
- System integration and debugging
- Edge case testing (pedestrian filter, partial crossings, timeout handling)
- Demo preparation and rehearsal
- Final presentation delivery
## 7.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 + state machine | ✓ Complete |
| Apr 29 | Progress demo: live violation detection working | ✓ Complete |
| Apr 30 – May 5 | Full integration: camera capture + alert + UART logging | ✓ Complete |
| May 6 | Integration update (Checkpoint B) | ✓ Complete |
| May 7 – May 12 | Bug fixes, threshold tuning, edge case testing, demo rehearsal | In progress |
| May 13 | Final demo & presentation | Pending |
# 8. Appendices & References
## 8.1 Source Code Repository:
https://github.com/MarwanMoh11/smart-redlight-tm4c123
## 8.2 References:
1. TI TM4C123GH6PM Datasheet — Texas Instruments, SPMS376E — https://www.ti.com/product/TM4C123GH6PM
2. TivaWare Peripheral Driver Library User's Guide — TI SPMU298D, included with SW-TM4C-2.2.0.295
3. FreeRTOS Reference Manual — Richard Barry, V11.1.0 — https://www.freertos.org/Documentation/RTOS_book.html
4. HC-SR04 Ultrasonic Sensor Datasheet — Elec Freaks
5. FSR 402 Integration Guide — Interlink Electronics — https://www.interlinkelectronics.com/fsr-402
6. Mastering the FreeRTOS Real Time Kernel — Richard Barry
7. CSCE 4301 Course Materials — Embedded Systems, Spring 2026, AUC