Devices & Components
16x2 LCD display with I²C interface
40 colored male-female jumper wires
Arduino Uno Rev3
Ultrasonic Sensor - HC-SR04
5V Mini Traffic Light Red Yellow Green 5mm LED Display Module
Battery 5V (PowerBank)
Piezo buzzer
Software & Tools
Arduino IDE
Project description
Code
Arduino IDE Sketch
cpp
You can just copy paste it :)
1// // 1. PIN DEFINITIONS & LIBRARIES 2#include <Wire.h> 3#include <LiquidCrystal_I2C.h> 4 5// Initialize the LCD at address 0x27 with 16 columns and 2 rows 6// Note: If 0x27 doesn't work, try 0x3F 7LiquidCrystal_I2C lcd(0x27, 16, 2); 8 9// Ultrasonic sensor pins 10const int trigPin = 9; 11const int echoPin = 10; 12 13// Traffic light LED pins 14const int ampelR = 8; // Red LED 15const int ampelY = 12; // Yellow LED 16const int ampelG = 13; // Green LED 17 18// Buzzer pin 19const int buz = 7; 20 21// // 2. VARIABLES FOR DISTANCE & MOVING AVERAGE 22long duration = 0; 23int distance = 0; 24 25const int numReadings = 5; 26int readings[numReadings]; 27int readIndex = 0; 28long total = 0; 29int averageDistance = 0; 30 31// // 3. TIME CONTROL VARIABLES (Global) 32unsigned long previousMillis = 0; // For buzzer timing 33unsigned long lastLCDUpdate = 0; // For LCD refresh timing 34const int lcdInterval = 200; // Update LCD every 200ms 35bool buzzerState = LOW; 36 37// // 4. SETUP 38void setup() { 39 Serial.begin(9600); 40 41 // LCD Initialization 42 lcd.init(); 43 lcd.backlight(); 44 lcd.setCursor(0, 0); 45 lcd.print("System Ready"); 46 delay(1000); 47 lcd.clear(); 48 49 pinMode(trigPin, OUTPUT); 50 pinMode(echoPin, INPUT); 51 pinMode(ampelR, OUTPUT); 52 pinMode(ampelY, OUTPUT); 53 pinMode(ampelG, OUTPUT); 54 pinMode(buz, OUTPUT); 55 56 for (int i = 0; i < numReadings; i++) { 57 readings[i] = 0; 58 } 59} 60 61// // 5. MAIN LOOP 62void loop() { 63 unsigned long currentMillis = millis(); 64 65 // // 6. SENSOR MEASUREMENT 66 digitalWrite(trigPin, LOW); 67 delayMicroseconds(2); 68 digitalWrite(trigPin, HIGH); 69 delayMicroseconds(10); 70 digitalWrite(trigPin, LOW); 71 72 duration = pulseIn(echoPin, HIGH, 25000); 73 distance = (duration * 0.034) / 2; 74 75 if (distance <= 0) { 76 distance = 200; 77 } 78 79 // // 7. CALCULATE MOVING AVERAGE 80 total = total - readings[readIndex]; 81 readings[readIndex] = distance; 82 total = total + readings[readIndex]; 83 readIndex = readIndex + 1; 84 85 if (readIndex >= numReadings) { 86 readIndex = 0; 87 } 88 averageDistance = total / numReadings; 89 90 // // 8. TRAFFIC LIGHT LOGIC 91 if (averageDistance <= 20 && averageDistance > 0) { 92 digitalWrite(ampelR, HIGH); digitalWrite(ampelY, LOW); digitalWrite(ampelG, LOW); 93 } 94 else if (averageDistance > 20 && averageDistance <= 50) { 95 digitalWrite(ampelR, LOW); digitalWrite(ampelY, HIGH); digitalWrite(ampelG, LOW); 96 } 97 else { 98 digitalWrite(ampelR, LOW); digitalWrite(ampelY, LOW); digitalWrite(ampelG, HIGH); 99 } 100 101 // // 9. BUZZER LOGIC 102 int pauseInterval = 0; 103 const int beepDuration = 10; 104 105 if (averageDistance <= 5 && averageDistance > 0) pauseInterval = 1; 106 else if (averageDistance <= 10) pauseInterval = 100; 107 else if (averageDistance <= 15) pauseInterval = 300; 108 else if (averageDistance <= 30) pauseInterval = 700; 109 else if (averageDistance <= 50) pauseInterval = 1200; 110 else pauseInterval = 0; 111 112 if (pauseInterval == 1) { 113 digitalWrite(buz, HIGH); 114 } 115 else if (pauseInterval == 0) { 116 digitalWrite(buz, LOW); 117 buzzerState = LOW; 118 } 119 else { 120 if (buzzerState == HIGH) { 121 if (currentMillis - previousMillis >= (unsigned long)beepDuration) { 122 digitalWrite(buz, LOW); 123 buzzerState = LOW; 124 previousMillis = currentMillis; 125 } 126 } 127 else { 128 if (currentMillis - previousMillis >= (unsigned long)pauseInterval) { 129 digitalWrite(buz, HIGH); 130 buzzerState = HIGH; 131 previousMillis = currentMillis; 132 } 133 } 134 } 135 136 // // 10. LCD DISPLAY LOGIC 137 // We update the LCD only every 200ms to avoid flickering 138 if (currentMillis - lastLCDUpdate >= lcdInterval) { 139 lastLCDUpdate = currentMillis; 140 141 lcd.setCursor(0, 0); 142 lcd.print("Distance: "); // Spaces clear old digits 143 lcd.setCursor(10, 0); 144 lcd.print(averageDistance); 145 lcd.print("cm"); 146 147 lcd.setCursor(0, 1); 148 if(averageDistance <= 20) lcd.print("Status: STOP! "); 149 else if(averageDistance <= 50) lcd.print("Status: Caution "); 150 else lcd.print("Status: Clear "); 151 } 152 153 // // 11. OUTPUT FOR MATLAB 154 Serial.println(averageDistance); 155 156 delay(30); 157}
MATLAB Visualisation
matlab
Generates a live plot of the distance in cm
1% Script for real-time visualization of HC-SR04 data 2% Important: Close the Arduino IDE Serial Monitor before running this script! 3 4% Serial port configuration 5clear; 6s = serialport("COM3", 9600); 7configureTerminator(s, "LF"); % Set the terminator to Line Feed 8 9% Initialize data arrays 10time = []; 11distance = []; 12 13% Create figure and plot 14figure; 15h = plot(NaN, NaN, 'LineWidth', 2); % Create a placeholder plot handle 16xlabel('Time (s)'); 17ylabel('Distance (cm)'); 18title('Real-time Distance Data from HC-SR04'); 19grid on; 20 21% Start timer for real-time visualization 22tic; 23 24% Read data in a loop 25while isvalid(s) 26 % Try to read a line from the serial port 27 try 28 dataString = readline(s); 29 value = str2double(dataString); 30 catch 31 % Ignore read errors and try again in the next iteration 32 continue; 33 end 34 35 % Check if conversion was successful and value is within range 36 if ~isnan(value) && value > 0 && value < 400 37 % Append new data points 38 time = [time, toc]; 39 distance = [distance, value]; 40 41 % Update the plot data 42 set(h, 'XData', time, 'YData', distance); 43 44 % Adjust the X-axis dynamically 45 current_time = toc; 46 if current_time > 10 % Show only the last 10 seconds 47 xlim([current_time - 10, current_time]); 48 else 49 xlim([0, 10]); 50 end 51 52 % Adjust Y-axis range (0-300 cm) 53 ylim([0, 300]); 54 55 % Force immediate drawing 56 drawnow limitrate; 57 end 58end 59 60% Close the serial port when the loop is terminated 61delete(s); 62clear s; 63disp('Serial connection closed.');
Downloadable files
MATLAB Visualisation
File for the Visualisation
visualHCSR04.m
Arduino Sketch
Code for HC-SR04, traffic light, buzzer, LCD, ...
sketchHCSR04_with_trafficlight.ino
Comments
Only logged in users can leave comments