Failed to connect to RPLidar with Slamtec A2M12 and Arduino Mega 2560

Happy New Year everyone!

I have tested my RPLidar with Slamtec RoboStudio and it is scanning and displaying the data correctly.

I have connected my RPLidar like this to my Arduino Mega 2560 board:
Blue > pin 2
Black > GND
Green > 19RX1
Yellow > 18TX1
Red > 5V

I downloaded the library zip from GitHub - robopeak/rplidar_arduino: RoboPeak RPLIDAR driver for Arduino and Arduino-compatible devices and included it in Arduino IDE. The baud is set to 115200 in the code and in the Arduino IDE:

#include <Arduino.h>
#include <RPLidar.h>

RPLidar lidar; // create an RPLidar object

void setup() {
  Serial.begin(115200);
  Serial.println("Starting Serial Communication...");
  
  // Initialize motor control pin (assuming it's pin 2 for PWM)
  pinMode(2, OUTPUT);  // Motor control pin (PWM)
  analogWrite(2, 255);  // Start the motor at full speed (PWM value of 255)

  // Connect to the RPLidar using the serial interface
  if (lidar.begin(Serial1)) {  // Use Serial1 (Pin 18 and Pin 19) on Arduino Mega
    Serial.println("RPLidar connected");
  } else {
    Serial.println("Failed to connect to RPLidar");
    while (1);  // Halt further execution if not connected
  }

  // Start scanning
  if (lidar.startScan()) {
    Serial.println("RPLidar scanning started");
  } else {
    Serial.println("Failed to start scan");
    while (1);  // Halt further execution if scan start fails
  }
}

void loop() {
  RPLidarMeasurement currentPoint = lidar.getCurrentPoint();
  float angle = currentPoint.angle;  // Get the angle of the current point
  float distance = currentPoint.distance;  // Get the distance of the current point
  
  Serial.print("Angle: ");
  Serial.print(angle);
  Serial.print(" Distance: ");
  Serial.println(distance);
  
  delay(100);  // Wait a bit before the next reading
}

which returns “Failed to connect to RPLidar”.

I have selected Arduino Mega Board as you can see in this screenshot:

using COM 9:
Screenshot 2025-01-14 142031

Somewhere I read to use Baud 256000, but when I put that in Serial.begin(256000) then is logs gibberish: “�n�36b}a>ihH��n�3Vba^iV+Hm’h]�” and serial monitor does not have the 256000 option.

Does anyone know what I am missing?

Some ideas:

  1. through the serial port debugging software first test the computer to lidar communication is normal.

  2. and then check whether the serial port of ESP32 is working properly. (You can try to computer and ESP32 send messages to each other, the baud rate is set to the same as the lidar)

  3. and then try the simplest code, ESP32 receive serial data output to see if you can receive the information of the lidar.

In addition, if the 3rd step is not normal, you need to check whether the electrical link between ESP32 and lidar is normal and whether the power supply capacity is sufficient.

https://wiki.slamtec.com/display/SD/RPLIDAR+FAQ