working-with-code-experiments

1. Required Components

2. Wiring Instructions

Follow these steps to connect the HC-SR04 sensor to your Arduino:

3. How It Works

The HC-SR04 sensor emits ultrasonic waves through the TRIG pin and measures the time taken for the waves to reflect back to the ECHO pin. Using the speed of sound (343 m/s), the distance is calculated.

4. Arduino Code

Copy and paste this code into the Arduino IDE:


// HC-SR04 Ultrasonic Sensor Pins
const int trigPin = 9;
const int echoPin = 10;

// Variables for storing the distance and pulse duration
long duration;
int distance;

void setup() {
  // Set up TRIG as output and ECHO as input
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
  // Initialize Serial Monitor
  Serial.begin(9600);
}

void loop() {
  // Clear the TRIG pin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  
  // Send a 10-microsecond pulse
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Measure the ECHO response time
  duration = pulseIn(echoPin, HIGH);

  // Calculate the distance in cm
  distance = duration * 0.034 / 2;

  // Output the distance to the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  // Wait before the next measurement
  delay(500);
}
            

5. Upload and Test

  1. Connect your Arduino to your PC using the USB cable.
  2. Open the Arduino IDE and paste the code above into a new sketch.
  3. Select the correct board and port in the IDE.
  4. Upload the code to your Arduino.
  5. Open the Serial Monitor to view real-time distance measurements in centimeters.

6. Additional Tips

7. Conclusion

Congratulations! You’ve successfully created an ultrasonic distance measurement tool using the HC-SR04 and Arduino. This versatile sensor is a gateway to exciting projects in robotics, home automation, and obstacle detection systems.

Contact Us

If you have any questions or inquiries, feel free to reach out to us at Microautomation.no@icloud.com .

Follow our Socials for the newest updates!