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:
- Arduino board (e.g., Arduino Uno)
- HC-SR04 ultrasonic sensor
- Jumper wires
- 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:
- Connect the VCC pin of the HC-SR04 to the 5V pin on the Arduino.
- Connect the GND pin of the HC-SR04 to the GND pin on the Arduino.
- Connect the Trig pin of the HC-SR04 to a digital pin on the Arduino (e.g., D2).
- 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:- Connect your Arduino to your computer using a USB cable.
- Open the Arduino IDE on your computer.
- Copy the provided code.
- Paste the code into the Arduino IDE.
- Select your Arduino board under the “Tools” menu.
- Select the port that your Arduino is connected to under the “Tools” menu.
- Click the “Upload” button to upload the code to your Arduino.
- 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.
+ There are no comments
Add yours