HC-SR04 with Arduino Mega 2560 R3

Wiring for the HC-SR04 ultrasonic distance on the Arduino Mega 2560 R3 (ATmega2560, 5 V logic), chosen with the same pin rules BoardPilot uses: default buses first, and no pins that are used for flash, USB, the debugger or booting.

Wiring

HC-SR04 pinRoleArduino Mega 2560 R3 pinNotes
VCCPower5VNeeds 5 V: use 5V
TRIGInput to the part22 (PA0)A 10 µs HIGH pulse starts a measurement
ECHOOutput from the part23 (PA1)
GNDGroundGND

Check before you power it on

Test code (Arduino)

void setup() {
  Serial.begin(115200);
  pinMode(22, OUTPUT);  // TRIG on 22
  pinMode(23, INPUT);   // ECHO on 23
}

void loop() {
  digitalWrite(22, LOW);  delayMicroseconds(2);
  digitalWrite(22, HIGH); delayMicroseconds(10);
  digitalWrite(22, LOW);
  long us = pulseIn(23, HIGH, 30000);
  Serial.println(us / 58.0);  // distance in cm
  delay(200);
}

Arduino board: arduino:avr:mega.

Questions

Which Arduino Mega 2560 R3 pins do I use for the HC-SR04?

VCC → 5V, TRIG → 22 (PA0), ECHO → 23 (PA1), GND → GND.

Does the HC-SR04 work with the Arduino Mega 2560 R3 at 5 V?

Yes: the HC-SR04 runs at 5 V and the Arduino Mega 2560 R3 uses 5 V signals, so no level shifting is needed.

BoardPilot checks this wiring in 3D as you build it, and finds crossed or missing wires on the real board.

Download BoardPilot

Full Arduino Mega 2560 R3 pinout · HC-SR04 ultrasonic distance: all pins and data

The HC-SR04 on other boards

Other parts on the Arduino Mega 2560 R3