In Progress
Lesson 1, Topic 1
In Progress

Code

18/10/2021

Copy-paste this code for programming Arduino.

The design of the Arduino Car Reverse Parking Sensor Circuit is very simple. Starting with the Ultrasonic Sensor, it has 4 pins: VCC, TRIG, ECHO and GND.

The VCC and GND are connected to +5V and GND of the power supply while the TRIG and ECHO are connected to Digital I/O pins 12 and 11 of Arduino respectively.

The buzzer used here is a 5V buzzer, starts beeping when the object comes too close to the sensor.

The code is very simple and if have followed our PORTABLE ULTRASONIC RANGE METER project, then you can easily understand this code as well.

As per the datasheet of the HC-SR04 Ultrasonic Sensor, its working is as follows:

The TRIG Pin should be high for a minimum of 10µS. After this, the Ultrasonic Sensor automatically sends 8 acoustic pulses of 40KHz frequency. The time between this and the reflected signal is calculated by reading the HIGH on the ECHO pin. The distance can be calculated as Time (for which ECHO is HIGH) * Velocity of Sound (340m/s) / 2. Using the same principle in the code, first, the TRIG is made HIGH for 10µS using the following lines of code.

 

 
#define trig 12
#define echo 11
 
void setup() {
 
  pinMode(trig,OUTPUT);
  pinMode(echo,INPUT);
  pinMode(5, OUTPUT);
  pinMode(13, OUTPUT);
  Serial.begin(9600); 
}
 
 
void loop() {
 
digitalWrite (trig,LOW);
delayMicroseconds(2);
digitalWrite (trig,HIGH);
delayMicroseconds(10);
digitalWrite (trig,LOW);
long t =pulseIn(echo,HIGH);
long cm = t/29/2;
Serial.println(cm);
delay (200);
 
digitalWrite (13, HIGH);
  delay (500);
digitalWrite (13, LOW);
 delay (500);
 
if(cm <= 100 && cm >= 60 ){
  digitalWrite (5, HIGH);
  delay (100);
  digitalWrite (5, LOW);
  delay (1000);
 
}
 
else if (cm <= 50 && cm >=30){
   digitalWrite (5, HIGH);
  delay (100);
  digitalWrite (5, LOW);
  delay (500);
 
}
 
else if (cm <= 30 && cm >=10){
   digitalWrite (5, HIGH);
  delay (80);
  digitalWrite (5, LOW);
  delay (1);
 
}
 
else if (cm <= 10 && cm >=0){
   digitalWrite (5, HIGH);
  delay (50);
 // digitalWrite (6, LOW);
//  delay (50);
 
}
 
else {
 digitalWrite (5, LOW);
// delay (50);
 
}
 
}