Interface Ultrasonic Sensor with Arduino
Arduino

Ultrasonic Sensor


Description

Here is some information about the HC-SR04 ultrasonic sensor, which can be used to determine the distance between an object and the sensor. The sensor is made up of an ultrasonic emitter and receiver. By measuring the time it takes for sound to travel from the emitter to the object and back to the receiver, the sensor can determine the distance. This article includes wiring diagrams, code examples, pinouts, and technical data to help you use the sensor effectively.


Sensor Details

The HC-SR04 ultrasonic sensor has four pins: Vcc+, Trigger, Echo, and Ground

The ultrasonic sensor has both an emitter and a transmitter that work at a frequency of 40kHz, which is beyond the hearing range of humans and most animals.

Tech Specs for the HC-SR04 Ultrasonic Sensor:

  • Operating Voltage: 3.3V to 5V
  • Current Consumption: 3mA
  • Range: .75in to 118in (2cm to 300cm)
  • Resolution: 1.2in (3cm)
  • Operating Frequency: 40kHz
  • Min Time Between Pulses: 50µs
  • Dimensions: .75in X 1.77in (2cm x 4.5cm)

Wiring Details
  • HC-SR04 Sensor GND to Arduino GND
  • HC-SR04 Sensor Vcc+ to Arduino +5V
  • HC-SR04 Sensor Echo to Arduino PIN 9
  • HC-SR04 Sensor Trigger to Arduino PIN 10

Circuit Image
Circuit Code
                                        
                                            

const int echoPin = 9;

const int triggerPin = 10;

// defines variables

long timetofly;

int distance;

void setup() {

pinMode(triggerPin, OUTPUT); // Sets trigger to Output

pinMode(echoPin, INPUT); // Set echo to Input

Serial.begin(9600); // Starts the serial communication

}

void loop() {

// Clears the triggerPin

digitalWrite(triggerPin, LOW);

delayMicroseconds(2);

// Sets the triggerPin on HIGH state for 10 micro seconds

digitalWrite(triggerPin, HIGH);

delayMicroseconds(10);

digitalWrite(triggerPin, LOW);

 

// Reads the echoPin, returns the travel time in microseconds

timetofly= pulseIn(echoPin, HIGH);

// Calculating the distance (Time to Fly Calculation)

distance= timetofly*0.034/2;

// Prints the distance on the Serial Monitor in CM

Serial.print(" Distance: ");

Serial.println(distance);

}