AJ-Explains-It-All
Published © GPL3+

Using HC-SR04 with Arduino

Calculate distances!

BeginnerFull instructions provided30 minutes2,014
Using HC-SR04 with Arduino

Things used in this project

Hardware components

Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
Arduino UNO
Arduino UNO
×1
Jumper wires (generic)
Jumper wires (generic)
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

schematic

Code

Code snippet #1

Plain text
const int pingPin = 9; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 10; // Echo Pin of Ultrasonic Sensor

void setup() {
   Serial.begin(9600); // Starting Serial Terminal (baud rate)
}

void loop() {
   long duration, inches, cm;
   pinMode(pingPin, OUTPUT); //tells the sensor to send a signal from trigger pin
   digitalWrite(pingPin, LOW);
   delayMicroseconds(2);
   digitalWrite(pingPin, HIGH); //sending the signal
   delayMicroseconds(10); // waiting 
   digitalWrite(pingPin, LOW);
   pinMode(echoPin, INPUT); //receiving back at the echo 
   duration = pulseIn(echoPin, HIGH); // we measured the duration by calculating the time difference for which the echo pin received the signal back from the trigger pin after reflection from the obstacle. This mechanism is also referred to as echolocation.
   inches = microsecondsToInches(duration); //called the function we created below
   cm = microsecondsToCentimeters(duration);
   Serial.print(inches); //printing to serial monitor
   Serial.print("in, ");
   Serial.print(cm);
   Serial.print("cm");
   Serial.println(); //command to invoke the serial monitor.
   delay(100);
}

long microsecondsToInches(long microseconds) {
   return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
   return microseconds / 29 / 2;
}

Credits

AJ-Explains-It-All

AJ-Explains-It-All

12 projects • 10 followers
Experienced embedded firmware and software developer. I have a great affinity towards ARM cortex based MCU's.

Comments