Codey OnlineArduino- & ESP32-componentenbibliotheek › HC-SR04
HC-SR04
Sensoren

HC-SR04

De HC-SR04 is een ultrasone afstandssensor die afstand meet door een geluidspuls te versturen en de terugkeer van de echo te timen. Hij werkt meestal op 5V en gebruikt een eenvoudige digitale trigger/echo-interface, waardoor hij makkelijk uit te lezen is in Arduino- en ESP32-projecten.

Breedte: 44.8 mm

Pinout — HC-SR04

Pin Signaal Beschrijving
Vcc power bottom-edge power pin hole, leftmost of the 4-pin header
Trig digital bottom-edge trigger pin hole, second from left
Echo digital bottom-edge echo pin hole, third from left
Gnd ground bottom-edge ground pin hole, rightmost of the 4-pin header

Voorbeeld-aansluitschema — HC-SR04

Van Naar Draad
board:5V x1:Vcc red
board:GND x1:Gnd black
board:D9 x1:Trig green
board:D10 x1:Echo blue

Voorbeeld-Arduinocode — HC-SR04

Dit voorbeeld is geschreven en compile-gecheckt voor de arduino-uno. Codey Online past het voor je aan naar elk ander ondersteund board.

// HC-SR04 ultrasonic distance sensor example
// Wiring:
// HC-SR04 Vcc -> 5V
// HC-SR04 Gnd -> GND
// HC-SR04 Trig -> D9
// HC-SR04 Echo -> D10

const int trigPin = 9;
const int echoPin = 10;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  digitalWrite(trigPin, LOW);
  Serial.println("HC-SR04 ready");
}

void loop() {
  // Send a 10 microsecond pulse to start a measurement
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echo pulse length (timeout after 30 ms)
  unsigned long duration = pulseIn(echoPin, HIGH, 30000UL);

  if (duration == 0) {
    Serial.println("Out of range or no echo");
  } else {
    // Convert time to distance in centimeters
    // Speed of sound approx. 343 m/s => 29.1 us per cm round trip
    float distanceCm = duration / 58.0;
    Serial.print("Distance: ");
    Serial.print(distanceCm, 1);
    Serial.println(" cm");
  }

  delay(500);
}

Vergelijkbare componenten

18650 Battery Shield with USB-C Charger and 5V Boost Converter

18650 Battery Shield with USB-C Charger and 5V Boost Converter

2.4 inch OLED Display I2C 3.3V

2.4 inch OLED Display I2C 3.3V

3.5 inch TFT LCD Shield

3.5 inch TFT LCD Shield

50kg Load Cell Weight Sensor

50kg Load Cell Weight Sensor

Bouw je Arduino- of ESP32-project met AI

Beschrijf wat je wilt bouwen. Codey Online schrijft de code, tekent het aansluitschema, compileert het en flasht je board rechtstreeks vanuit de browser.

Gratis starten