> For the complete documentation index, see [llms.txt](https://guides.mccaskeyrobotics.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://guides.mccaskeyrobotics.org/arduino/ultrasonic-range-sensor.md).

# Ultrasonic Range Sensor

### Parts:&#x20;

1 – Arduino Uno

1 – Ultrasonic Sensor

Assorted Wires

### Wiring:&#x20;

![](/files/jc0LoSvSIo6UY3Sg63l1)

| Ultrasonic | Arduino |
| ---------- | ------- |
| Vcc        | 5V      |
| Trig       | 13      |
| Echo       | 12      |
| GND        | Gnd     |

### Code:&#x20;

```
//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);
}
```
