The Nano is the breadboard-friendly twin of the Uno, which makes it the usual brain for blind sticks, parking sensors and small robots built around the HC-SR04.
Everything runs at 5 V: Trig on D2, Echo on D3. The sketch prints the distance five times a second and lights the on-board LED when something is closer than 20 cm.
Wiring
| Arduino Nano | HC-SR04 ultrasonic sensor | Wire | Notes |
|---|---|---|---|
| 5V | VCC | red | |
| D2 | Trig | green | |
| D3 | Echo | blue | |
| GND | GND | black |
5 V (HC-SR04P / RCWL-1601: 3–5.5 V) part, 5 V board. The classic HC-SR04 needs 5 V and its ECHO pin outputs 5 V. On a 3.3 V board (ESP32, Pico) send ECHO through a 1 kΩ / 2 kΩ divider. A 3.3 V trigger signal is enough for TRIG.
Board quirks
- The Nano is a 5 V ATmega328P board like the Uno, so Echo needs no divider.
- Clone Nanos use a CH340 USB chip and the old bootloader: if upload fails, pick Tools → Processor → ATmega328P (Old Bootloader).
- The Nano sits on a breadboard; keep the HC-SR04 at the board edge so the transducers aren’t blocked by wires.
Code
// HC-SR04 ultrasonic distance sensor on an Arduino Nano.
// VCC → 5V, Trig → D2, Echo → D3, GND → GND. The Nano is a 5 V board, so no divider is needed.
const uint8_t TRIG_PIN = 2;
const uint8_t ECHO_PIN = 3;
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
digitalWrite(TRIG_PIN, LOW);
}
void loop() {
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long us = pulseIn(ECHO_PIN, HIGH, 30000UL); // ~5 m max
if (us == 0) {
Serial.println(F("Out of range or no echo"));
} else {
float cm = us * 0.0343 / 2.0;
Serial.print(F("Distance: "));
Serial.print(cm, 1);
Serial.println(F(" cm"));
digitalWrite(LED_BUILTIN, cm < 20 ? HIGH : LOW); // on-board LED when something is close
}
delay(200);
}// HC-SR04 ultrasonic distance sensor on an Arduino Nano.
// VCC → 5V, Trig → D2, Echo → D3, GND → GND. The Nano is a 5 V board, so no divider is needed.
const uint8_t TRIG_PIN = 2;
const uint8_t ECHO_PIN = 3;
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
digitalWrite(TRIG_PIN, LOW);
}
void loop() {
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long us = pulseIn(ECHO_PIN, HIGH, 30000UL); // ~5 m max
if (us == 0) {
Serial.println(F("Out of range or no echo"));
} else {
float cm = us * 0.0343 / 2.0;
Serial.print(F("Distance: "));
Serial.print(cm, 1);
Serial.println(F(" cm"));
digitalWrite(LED_BUILTIN, cm < 20 ? HIGH : LOW); // on-board LED when something is close
}
delay(200);
}Expected serial output
Distance: 31.2 cm
Distance: 31.3 cm
Distance: 14.8 cmDistance: 31.2 cm Distance: 31.3 cm Distance: 14.8 cm