Ultrasonic Range Sensor

Parts:

1 – Arduino Uno

1 – Ultrasonic Sensor

Assorted Wires

Wiring:

Ultrasonic
Arduino

Vcc

5V

Trig

13

Echo

12

GND

Gnd

Code:

//here we declare what each pin will be on arduino board
int trigPin = 13;
int echoPin = 12;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  //gives the user half a second to put down the car after turning the switch  delay(500);
}
void loop() {
  // get the distance away from the sensor for an object
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
  //print distance for troubleshooting
  if (distance >= 200 || distance <= 0) {
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.print(" cm\t");
    Serial.print(distance / 2.54);
    Serial.println(" in");
  }
  delay(20);
}

Last updated

Was this helpful?