Ultrasonic Sensor HC-SR04 with Arduino



    Sohail Gulam


    Ultrasonic Sensor HC-SR04 is a sensor that can measure distance. It emits an ultrasound at 40 000 Hz (40kHz) which travels through the air and if there is an object or obstacle on its path It will bounce back to the module. Considering the travel time and the speed of the sound you can calculate the distance.

    The configuration pin of HC-SR04 is VCC (1), TRIG (2), ECHO (3), and GND (4). The supply voltage of VCC is +5V and you can attach TRIG and ECHO pin to any Digital I/O in your Arduino Board.

    #define echoPin 2 // attach pin D2 Arduino to pin Echo of HC-SR04
    #define trigPin 3 //attach pin D3 Arduino to pin Trig of HC-SR04
    // defines variables
    long duration; // variable for the duration of sound wave travel
    int distance; // variable for the distance measurement
    void setup() {
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
      pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
      Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
      Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
      Serial.println("with Arduino UNO R3");
    void loop() {
      // Clears the trigPin condition
      digitalWrite(trigPin, LOW);
      // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
      digitalWrite(trigPin, HIGH);
      digitalWrite(trigPin, LOW);
      // Reads the echoPin, returns the sound wave travel time in microseconds
      duration = pulseIn(echoPin, HIGH);
      // Calculating the distance
      distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
      // Displays the distance on the Serial Monitor
      Serial.print("Distance: ");
      Serial.println(" cm");
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.