> 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). Agents can also search and read this documentation through its [MCP server](https://guides.mccaskeyrobotics.org/~gitbook/mcp).

# Ultrasonic Range Sensor

### Parts:&#x20;

1 – Arduino Uno

1 – Ultrasonic Sensor

Assorted Wires

### Wiring:&#x20;

![](https://3423273789-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjRgHmD322MUgRPOyqMLh%2Fuploads%2FcdA1JgbqX9i4cgtoRp4c%2Fultrasonic.svg?alt=media\&token=f14d1b3d-45ea-401e-a485-27f52d2eb704)

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