Home        Store        Docs        Blog

Ping Sonar and Arduino Mega

I am trying to connect a Ping sonar to an Arduino Mega, since I want to use the sonar at 115200 baud.

I’m using the pin assignments from here: https://www.arduino.cc/reference/en/language/functions/communication/serial/

I’ve changed the Rx pin to 19 and the Tx pin to 18 in the sample code, but all I get is the error message in the serial monitor window.

Since I am no longer using a software serial port, what change is required in these lines from the sample code?

SoftwareSerial pingSerial = SoftwareSerial(arduinoRxPin, arduinoTxPin);
static Ping1D ping { pingSerial };

@sdzafovic We have a step-by-step guide for how to setup the Ping with an Arduino: https://bluerobotics.com/learn/using-the-ping-sonar-with-an-arduino/

Would you mind trying that out and letting us know how far you get? It should be the same for the Mega.

I want to use the Mega since it has extra hardware serial ports.

The example includes reducing the baud rate of the sonar to 9600, since this is the maximum for the SoftwareSerial function. I want to run the Ping using hardware serial ports at 115200 baud.

I changed the TX and RX pins in the same code to hardware port 1 (pins 18 and 19 on the Mega) and ran the code. All I got on the serial monitor was error messages (ping did not initialize).

I am also confused about these lines of code:

SoftwareSerial pingSerial = SoftwareSerial(arduinoRxPin, arduinoTxPin);
static Ping1D ping { pingSerial };

Since I’m not using SoftwareSerial, what do I use instead?

Here you go! I threw this together on a Mega 2560. All you need to do is hook it up to Serial1 and then change out the serial port and baud rate.


Ping White TX wire -> Serial1 RX (Pin 19)
Ping Green RX wire -> Serial1 TX (Pin 18)


#include "ping1d.h"

static const uint8_t arduinoRxPin = 19; //Serial1 rx
static const uint8_t arduinoTxPin = 18; //Serial1 tx

static Ping1D ping { Serial1 };

static const uint8_t ledPin = 13;

void setup()
  pinMode(ledPin, OUTPUT);
  Serial.println("Blue Robotics ping1d-simple.ino");
  while (!ping.initialize()) {
    Serial.println("\nPing device failed to initialize!");
    Serial.println("Are the Ping rx/tx wired correctly?");
    Serial.print("Ping rx is the green wire, and should be connected to Arduino pin ");
    Serial.println(" (Arduino tx)");
    Serial.print("Ping tx is the white wire, and should be connected to Arduino pin ");
    Serial.println(" (Arduino rx)");

void loop()
  if (ping.update()) {
    Serial.print("Distance: ");
    Serial.print("\tConfidence: ");
  } else {
    Serial.println("No update received!");

  // Toggle the LED to show that the program is running
  digitalWrite(ledPin, !digitalRead(ledPin));

Hope that works for you


That worked great. Thank you.

I was confused with how to implement the second serial port, but it is clear now.

Yep, they are just a little different. I’ll get this added to the guide.

1 Like