Operácie

Sonic

Zo stránky SensorWiki

Verzia z 18:17, 27. január 2026, ktorú vytvoril Balogh (diskusia | príspevky)

Študijné materiály na workshop E-design



Ultrazvukový senzor BEZ použitia špeciálnej knižnice

To use the HC-SR04 ultrasonic sensor with Arduino without libraries, send a 10µs HIGH pulse to the Trig pin, then measure the resulting Echo pin pulse duration using pulseIn(). Calculate distance in cm by dividing duration by 58.2 or \(0.0343\div 2\). 

Wiring: 

 VCC: 5V
 GND: GND
Trig: Digital Pin 9 (or any digital I/O)
Echo: Digital Pin 10 (or any digital I/O) 


Code Example:

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


/* Arduino code  */


void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // Clear trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  // Reads the echoPin, returns sound wave travel time in microseconds
  long duration = pulseIn(echoPin, HIGH);
  
  // Calculating the distance (speed of sound is ~343m/s or 0.0343 cm/us)
  float distanceCm = duration * 0.0343 / 2;
  
  // Print to Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distanceCm);
  Serial.println(" cm");
  
  delay(100); // Small delay to avoid interference
}


Key Principles: 

  • Trigger Pulse: A 10-microsecond high pulse is required to initiate the sensor's 8-cycle ultrasonic burst,
  • Echo Pulse: The echo pin goes high for the same amount of time it takes for the sound to travel to the object and back,
  • Calculation: \(\text{Distance}=\frac{\text{Duration}\times \text{Speed\ of\ Sound}}{2}\).
  • Range: The sensor measures distances from 2cm up to 400cm