티스토리 뷰

반응형

HC-SR04 Control in Arduino: The Ultimate Guide with Source Code

The HC-SR04 is an affordable and popular ultrasonic distance sensor that is widely used in various applications. This guide provides a comprehensive overview of how to control the HC-SR04 in Arduino, including the necessary hardware connections, software setup, and source code.

What is the HC-SR04 Ultrasonic Distance Sensor?

The HC-SR04 is a compact and easy-to-use ultrasonic distance sensor that can measure distances from 2 cm to 400 cm with a precision of 3 mm. It operates by sending out a 40 kHz ultrasonic wave and measuring the time it takes for the wave to bounce back from an object. The distance to the object can then be calculated based on the time it took for the wave to travel to the object and back.

Hardware Connections

Before we dive into the software setup, let's first discuss the necessary hardware connections. You will need:

  • An Arduino board
  • An HC-SR04 ultrasonic distance sensor
  • Jumper wires
  • A breadboard (optional)

To connect the HC-SR04 to the Arduino board, follow these steps:

  1. Connect the VCC pin on the HC-SR04 to the 5V pin on the Arduino board.
  2. Connect the GND pin on the HC-SR04 to the GND pin on the Arduino board.
  3. Connect the TRIG pin on the HC-SR04 to digital pin 7 on the Arduino board.
  4. Connect the ECHO pin on the HC-SR04 to digital pin 8 on the Arduino board.

Software Setup

Now that the hardware connections are done, let's move on to the software setup. You will need to download and install the Arduino software, which is available for free on the official Arduino website.

Once you have installed the software, follow these steps:

  1. Launch the Arduino software and select the appropriate board and serial port from the Tools menu.
  2. Copy and paste the following code into the Arduino software:
#define TRIG 7
#define ECHO 8

void setup() {
  Serial.begin(9600);
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
}

void loop() {
  long duration, distance;
  
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);
  
  duration = pulseIn(ECHO, HIGH);
  distance = (duration / 2) / 29.1;
  
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  
  delay(500);
}

    3. Upload the code to the Arduino board.

    4. Open the Serial Monitor from the Tools menu to view the distance readings from the HC-SR04.

Interpreting the Results

The code above calculates the distance to an object using the HC-SR04 ultrasonic distance sensor. The distance is displayed in centimeters on the Serial Monitor. You can use this information to control other devices or to build your own projects that require precise distance measurements.

Conclusion

In this guide, we have discussed the basics of the HC-SR04 ultrasonic distance sensor and how to control it in Arduino. With a few simple hardware

반응형