Using Ultrasonic Sensor with Arduino - Measure Distance with Arduino




Connections


- The Ultrasonic sensor VCC to 5v on Arduino
- The Ultrasonic sensor GND to GND on Arduino
- The Ultrasonic sensor Trig to D9 on Arduino
- The Ultrasonic sensor  Echo to D10 on Arduino



Arduino Sketch


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

long duration;
int distance;

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

}

void loop() {
  // Clears the trigPin
  digitalWrite( trigPin , LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite( trigPin , LOW);
  // Reads the echoPin, returns the sound wave 
  // travel time in microseconds 
  duration = pulseIn( echoPin , HIGH);

  distance = duration * 0.034 / 2;

  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);

}

ความคิดเห็น