Devices & Components
Arduino Uno Rev3
Jumper wires (generic)
Ultrasonic Sensor - HC-SR04 (Generic)
Buzzer
Breadboard (generic)
Software & Tools
Arduino IDE
Project description
Code
Parking Sensord
arduino
1/************************************************************** 2 * PARKING SENSOR WITH HC-SR04 * 3 * * 4 * This code receives data from the HC-SR04 proximity * 5 * sensor, analyses them, sends them to the serial monitor * 6 * and produces intermittent sounds to warn of an obstacle. * 7 **************************************************************/ 8 9// Definition of trigger, echo, beep pins and other constants 10#define trigger 2 11#define echo 3 12#define beep 11 13#define beep_start 100 14#define min_distance 5 15 16// Definition of sound speed (centimetres / microsecond) 17#define c 0.0343 18 19// Definition of the variables 20long tempo; 21float space; 22 23void setup() { 24 // Definition of input and output 25 pinMode(trigger, OUTPUT); 26 pinMode(echo, INPUT); 27 pinMode(beep, OUTPUT); 28 29 // Serial communication initialisation (optional) 30 Serial.begin(9600); 31} 32 33void loop() { 34 // Before measurement, the trigger is set to low level 35 digitalWrite(trigger, LOW); 36 delayMicroseconds(5); 37 38 // Send one pulse (trigger goes high level for 10 microseconds) 39 digitalWrite(trigger, HIGH); 40 delayMicroseconds(10); 41 digitalWrite(trigger, LOW); 42 43 // Reading echo, via pulseIn, which returns the duration of the impuse (in microseconds) 44 // The acquired data is then divided by 2 (forward and backward) 45 tempo = pulseIn(echo, HIGH) / 2; 46 // Computation of distance in centimetres 47 space = tempo * c; 48 49 // space is displayed in the serial monitor ([Ctrl] + [Shift] + M) 50 // approximated to the first decimal place 51 Serial.println("Distanza = " + String(space, 1) + " cm"); 52 53 // If the distance is less than one metre 54 if (space < beep_start) { 55 // Emits sounds at intervals proportional to distance (1 m = 400 ms) 56 tone(beep, 1000); 57 delay(40); 58 // Below min_distance cm it emits a continuous sound 59 if (space > min_distance) { 60 noTone(beep); 61 delay(space * 4); 62 } 63 } 64 // Waits 50 milliseconds before another measurement 65 delay(50); 66}
Downloadable files
Assembly diagram
How to assembly the circuit. Note that the buzzer was placed in pin 11 because, in this way, it can also be plugged directly on Arduino.
Assembly diagram

Comments
Only logged in users can leave comments