How to connect Arduino with HC-SR04 ultrasonic distance sensor

Connecting an Arduino with an HC-SR04 ultrasonic distance sensor is a common and straightforward task. The HC-SR04 sensor uses ultrasonic waves to measure distance. Here’s a step-by-step guide:

Components Needed:

  1. Arduino board (e.g., Arduino Uno)
  2. HC-SR04 ultrasonic sensor
  3. Jumper wires
  4. Breadboard (optional, for easier connections)

Wiring Connections:

HC-SR04 Pinout:

  • VCC: Connect to 5V on Arduino
  • Trig: Connect to a digital pin on Arduino (e.g., D2)
  • Echo: Connect to a digital pin on Arduino (e.g., D3)
  • GND: Connect to GND on Arduino

Wiring Steps:

  1. Connect the VCC pin of the HC-SR04 to the 5V pin on the Arduino.
  2. Connect the GND pin of the HC-SR04 to the GND pin on the Arduino.
  3. Connect the Trig pin of the HC-SR04 to a digital pin on the Arduino (e.g., D2).
  4. Connect the Echo pin of the HC-SR04 to another digital pin on the Arduino (e.g., D3).

Arduino Code:


// Define the pins
const int trigPin = 2;
const int echoPin = 3;

// Define variables
long duration;
int distance;

void setup() {
// Initialize serial communication
Serial.begin(9600);

// Set trigPin as OUTPUT and echoPin as INPUT
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop() {
// Generate a pulse on the trigPin to trigger the sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Measure the duration of the pulse on the echoPin
duration = pulseIn(echoPin, HIGH);

// Calculate the distance based on the speed of sound (343 meters/second)
distance = duration * 0.0343 / 2;

// Print the distance to the Serial Monitor
Serial.print(“Distance: “);
Serial.print(distance);
Serial.println(” cm”);

// Wait for a short time before taking the next measurement
delay(500);
}

Uploading and Running the Code:
  1. Connect your Arduino to your computer using a USB cable.
  2. Open the Arduino IDE on your computer.
  3. Copy the provided code.
  4. Paste the code into the Arduino IDE.
  5. Select your Arduino board under the “Tools” menu.
  6. Select the port that your Arduino is connected to under the “Tools” menu.
  7. Click the “Upload” button to upload the code to your Arduino.
  8. Open the Serial Monitor to view the distance measurements.

This code continuously measures the distance using the HC-SR04 sensor and prints the result to the Serial Monitor. Adjustments can be made to suit your specific project requirements.

 

You May Also Like

+ There are no comments

Add yours