0

$USD

$USD
TUTORIALS Laser Radar

DFRobot LIDAR Sensors – Getting Started with LIDAR

DFRobot Jul 16 2018 3845

Introduction

One advancing technology that has been impossible to ignore lately has been the work with self driving vehicles.  These vehicles have gone from scientific curiosity to mainstream within a few short years and soon we’ll be seeing them as regular traffic on our streets.

A very distinctive component in a self driving vehicle is the spinning LIDAR sensor mounted on the top of the vehicle.  This is one of the principal components in self driving vehicles as it collects data regarding the surrounding area to allow the navigation systems to guide the vehicle safely.


LIDAR may seem like a sophisticated system and it is, however recent cost reductions have made it possible for experimenters like you and me to work with LIDAR for our own projects.

The folks at DFRobot have a number of low cost LIDAR devices available and they were kind enough to supply me with a couple of them. So follow along and learn how you can bring cutting edge technology like LIDAR to your own robotics projects.

What is LIDAR?

LIDAR is a method of using focused light beams to detect distant objects. It works very much like RADAR and in fact the mnemonic “LIDAR” was initially a fusion of the words “RADAR” (Radio Detection And Ranging) and “Light”.

A more common definition of “LIDAR” is Light Inspection, Detection and Ranging, this more accurately defines LIDARs role in inspection applications.  Some publications use the letter “L” in “LIDAR” to mean “Laser” although a LIDAR unit can be built using light sources other than a laser.

LIDAR functions by sending out a light beam and measuring its reflected signal. Several aspects of the signal are measured including the light intensity and angle. These measurements can be used to calculate the distance to the reflecting object as well as some information regarding its reflectivity.

In many applications the light beam is moved or scanned to get several points of reflection, this data is often displayed in a three dimensional array known as a “point cloud”.

In addition to its application in self driving vehicles LIDAR also finds use in many scientific applications including weather forecasting and climate sciences, urban planning, deep sea exploration, surveying, aeronautics and forestry . It even has extraterrestrial uses, LIDAR has been used to scan both the Moon and Mars and it will undoubtedly be a key component in the robotic exploration of other worlds.

LIDAR History

LIDAR was conceived shortly after the development of the laser, early work on LIDAR was documented in 1963. The high cost of laser equipment kept LIDAR use confined to government and military agencies for several decades.

LIDAR requires a strong focused light source, a sensitive and fast receiver and a quick processor to analyze the signal and produce meaningful data.  Super fast processors like the ones used in video games have brought the processing costs down drastically.

The development of semiconductor lasers and high powered LEDs has brought the cost of LIDAR down to the level where home robotics experimenters like ourselves can now purchase inexpensive LIDAR units for use in our own projects.

The two devices we will be looking at today are perfect examples of modern low cost LIIDR sensors.

LIDAR Robotics Applications

There are a number of cases in which you would employ LIDR in the design of a robot.

LIDAR sensors function in a similar manner to the familiar ultrasonic sensors that we have used before. Like their ultrasonic counterparts they can be used for collision avoidance and distance measurement.

As a stationary LIDAR sensor is several times more expensive than an ultrasonic sensor ne needs to consider what advantages the use of LIDAR would have over a common HC-SR04.

The LIDAR sensor is more accurate and can pinpoint a much finer area. It can also be polled up to 100 times per second so it is less likely to miss a the sudden appearance of an object in its path.  LIDAR sensors can also cover a greater range than ultrasonic sensors, the two sensors we are looking at today have ranges of 12m or 4 feet.

By coupling a LIDAR sensor with a pan and tilt or spinning mechanism we can get three dimensional data very quickly, a fat that is not possible for an ultrasonic sensor due to its slow response time. The advanced device, the RPLIDAR unit, has a spinning platform built into the unit.

In designing a robot it is desirable to make use of both ultrasonic and LIDAR sensors.  Some objects do not reflect infrared light well and are better detected with ultrasonic sound, conversely some objects are better detected with light. By combining readings from both sensors we can get a more accurate idea of our robots position in the world.

How LIDAR Works

The principle of LIDAR operation is pretty simple. A focused light beam is aimed at an object and a sensor looks for its reflection. If the beam is detected its intensity and angle (or phase) is measured. These values are then plugged into an equation run by a fast onboard computer to determine the reflecting objects position and characteristics.

By “sweeping” the beam and receiver array mechanically we can quickly build up a 3D “image’ of the surrounding area. This is often displayed in a “point cloud” to help us humans visualize what the LIDAR is “seeing”.

Of course LIDAR is not the only method that can be used to sense external surroundings. Let’s see how LIDAR compares to other remote position sensing method.

LIDAR vs Other Technologies

There are a few other technologies that we can use to provide our intelligent machines with knowledge about the world around them.

LIDAR vs Ultrasonic Sensors

We have looked at ultrasonic sensors before, specifically the popular HC-SR04 devices. They are inexpensive and easy to use components that take up about the same amount of space as the stationary LIDAR sensor we will be looking at today. They also consume about the same amount of current.

Ultrasonic sensors work on essentially the same principle as our LIDAR sensors except they use ultrasonic sound instead of infrared light. They have a range from about 2 cm to 4m so they can cover items at closer range than LIDAR but not as far.

Ultrasonic sound is not as directional as light so an ultrasonic sensor can’t be used to create a point cloud. As sound travels much slower than light you are limited to how much data you can gather in a short period of time. And not all objects reflect ultrasonic sound, some items absorb  sound and don’t reflect enough of it back to get a good reading.

Still ultrasonic sensors have a lot of good points in their favor. They are much cheaper than LIDAR, can detect objects reasonably close and are very easy to use.

LIDAR vs IR Light Sensor

This is a bit of a confusing comparison as a LIDAR device is a form of IR Light Sensor.  The type of IR Light Sensor that I’m referring to is the sort with an IR LED and receiver diode, used for collision detection applications. These assemblies output a pulse when they detect an object at or closer than a preset distance. You can adjust the distance they trigger at using an onboard potentiometer.

These devices are cheap and as they also work using IR light beams they are very fast. They have a range that extends from just a few millimeters to about 10 cm, so they work at a much closer range than LIDAR does.

These simple IR light sensors don’t provide any data on the quality of the returned light or an actual distance measurement.They are best used as alarm type sensors that trigger when an external object is detected at a preset range. Great to send an interrupt to tell your robot that it’s about to hit a wall!

LIDAR vs RADAR

LIDAR is based upon the same principle as RADAR except it makes use of light beams instead of high frequency radio waves.

A full fledged RADAR array isn’t that practical for a small robot project, however small microwave and radar sensors are available. These can be used in similar applications as LIDER and have similar or greater ranges and capabilities. Some items absorb or pass radio waves and are not detected well using RADAR.

As RADAR is based upon radio waves (microwaves) it is as fast as LIDAR, LIDAR does have an advantage in resolution but RADAR is still pretty capable. At the low power levels required for a small sensor RADAR won’t pose a threat to human or animal health but will consume a bit more current than LIDAR sensors.

Self driving vehicles use a combination of LIDAR and RADAR sensors.

So as you can see there are advantages and disadvantages of all types of sensors, including LIDAR. In a complex robot project you would likely use most, if not all, of the above technologies.
Now that we have seen how LIDAR stacks up against other technologies let’s take a look at teh two LIDAR devices that we will be working with today.

DFRobot LIDAR Sensors

DFRobot were kind enough to send me not one but two LIDAR devices from their wide assortment of robotics products.

TF Mini LIDAR

The TF Mini LIDAR is a fixed position LIDAR source-sensor array that retails for an unbelievably low price. Despite its minimal cost it has some impressive specifications:

  • Range of 30 cm to 12m (1 foot to 40 feet)
  • Accuracy to 0.5 cm within the range
  • Up to 100 scans per second
  • Low power consumption
  • Built in processor with serial I/O

<insert TF Mini>
The device supplied by DFRobot came packaged in a small box with internal anti static packing foam. In addition to the TF Mini LIDAR itself the package also contained two cables, a cable with a mini connector on each end and a cable that has a mini connector on one end and four single pin DuPont connectors on the other end.

The latter cable is perfect for experimenting with the TF Mini LIDAR device.

TF Mini LIDAR Connections

There are four connections on the TF Mini, as follows:

  • GND – The Ground Connection.
  • VCC – Power supply, the TF MIni requires 5 volts DC.
  • TXD – Transmit Data. Note that this is a 3.3 volt logic signal.
  • RXD – Receive Data. Again this accepts 3.3 volt logic.
The connections are on a mini connector and DFRobot supplied two cables that can be used with the connector. The one with the four DuPont pins on the other end is very useful for connecting the TF Mini LIDAR to a solderless breadboard.


Low Voltage

One thing to be aware of when using the TF Mini is that the logic pins on the device use 3.3 volt logic as opposed to the 5 volt logic you may be more accustomed to using.  This needs to be taken into consideration when interfacing the TF Mini LIDAR to a 5 volt logic device like an Arduino Uno.

The rules in dealing with logic systems that have different voltage levels is as follows:

A 3.3 volt OUTPUT can be connected directly to a 5 volt INPUT. This arrangement is not only safe, it also works as the 5 volt input will have a threshold of 2.8 volts for a digital one, within the range of the 3.3 volt output.

A 5 volt OUTPUT cannot be connected directly to a 3.3. Volt INPUT. Doing so could possibly damage the 3.3 volt logic device!  Some method of voltage reduction or conversion is required.
So technically the TX output of the TF Mini LIDAR is fine to connect to an input on an Arduino Uno. But you’ll need to do something about the RX input as it could be damaged by the 5 volt output from the Arduino (or whatever other 5 volt device you are interfacing it to).

The best way to handle this situation is with the use of inexpensive logic level converters. These are available in a number of channels ranging from 1 to 16 and are bidirectional meaning they convert both the input and output voltages on both sides.

I’m making use of a popular 2-channel logic level converter in my work with the TF Mini LIDAR. These devices are available for very little money and can be found on eBay, Amazon and any well stocked electronics distributor.  They are popular as two channels is perfect for converting logic levels in I2C bus systems and any other system (such as ours) that uses transmit and receive lines.

I’d suggest you pick up a handful of these handy devices for use with the TF Mini LIDAR as well as a number of other applications you are sure to have for them.

RPLIDAR

Unlike the simple TF Mini LIDAR device the RPLIDAR is a full 360 degree scanning LIDAR unit.  It’s available at DFRobot for an unbelievable low price yet despite its low cost it has an impressive list of features.

The RPLIDAR has the following features:

Runs clockwise 360 degree scans.
Can take more than 8000 distance data measurements per second.
Scan rate of 2 to 10 Hz. This means you can do a full 360 degree scan 2 to 10 times per second, the rate being controller via motor speed.
12 meter detection range (about 40 feet).
1 degree angular resolution.
0.2 cm distance resolution.
Runs on 5 volt power supply (motor can be supplied separately, it also uses 5 volts)

Open source SDK and tools

Integrates with ROS (Robot Operating System). You can also integrate it with an Arduino or Raspberry Pi.

Includes serial to USB convertor to connect directly to a computer with a USB port.

One very nice feature of the RPLIDAR is that it does not use a slip-ring to make connections to the LIDAR laser transmitter and receiver on the revolving platform. Instead it uses a proprietary wireless and optical connection, eliminating a potential point of electrical failure and/or data corruption.

<INSERT RPLIDAR>

Unpacking the RPLIDAR

The RPLIDAR arrived from DFRobot superbly packaged, it reminds me of the packaging used with some Apple or other high-end electronics products.  

The device is encased in a couple of layers of protective foam and inserts in the foam are provided for the serial to USB convertor board. A small box on top of the packaging contained a reference card and a short cable to connect the RPLIDAR to the serial to USB board.

The unit itself is completely assembled and the build is of excellent quality. The spinning top is nicely finished in a stealthy looking black with a couple of “eye holes” for the laser and optical sensor.

On the bottom of the unit you can see the motor attached to a pulley to drive the rotating platform, a simple but effective design. There is a 7-pin connector to interface the RPLIDAR to the outside world, you can attach this to the supplied cable and use either the serial to USB convertor or take the connections directly to use with your Arduino or other controller.

A set of spacers are mounted on the unit to lift it up to allow the electrical connections to be made.

Getting Started

So now that we’ve seen the two devices that DFRobot so kindly provided I’ll outline the game plan here.

Obviously there is a LOT we can do with LIDAR, both the stationary TF Mini LIDAR and the rotating RPLIDAR unit.  Much more than can be covered in one article or video.

So I’m going to start off small. I’ll show you how to hook up both units, the TF Mini to an Arduino and the RPLIDAR to both an Arduino and to a computer (the latter being as easy as plugging in a cable and running some software).

Then after that we’ll leave these alone today. And in the next installment in the series I’ll do a seperate project for each device.  Something to really show off the LIDAR capabilities.

So let’s begin!

Using the TF Mini LIDAR with Arduino

We will start with the TF Mini LIDAR, it’s the least expensive of the two and is pretty easy to use as long as you keep in mind those logic voltage level considerations I brought up earlier.

As we saw when the device was unpacked there is an included interface cable that has four female dupont connectors on one end.  We will use this cable to hook up our RPLIDAR to the logic level converter module and the Arduino.

Speaking of logic level converter you will need one, I’m using a 2-channel unit so if you use a different one you may need to adjust the pinouts to match your component.

TF Mini LIDAR Arduino Hookup

The hookup of the TF Mini LIDAR unit to the Arduino is shown here.

Note that the logic level converter uses both a 5 volt and 3.3 volt power supply, both are taken from the Arduino Uno.

In our hookup pin 10 of the Arduino is used as a receive pin for the data from the TX output of the TF Mini LIDAR. That data runs through channel “A” of the convertor.  Pin 11 of the Arduino is used as a transmit pin for data sent to the RX input on the TF Mini. This runs through channel “B” of the convertor, protecting the RX input from the 5 volt logic used in the Arduino.

The chart on the hookup diagram should assist you in making the correct connections.

TF Mini LIDAR Arduino Sketch

Now that we have everything hooked up let’s run a sketch to demonstrate the capabilities of the TF Mini LIDAR unit.

We are going to take the easy road and install a library for the TF Mini LIDAR into our Arduino IDE and then run a sample sketch included with the library.

The TF Mini Library from Peter Jansen is available through your Arduino IDE LIbrary Manager.

Open the Arduino IDE

Go to the Sketch menu then highlight Include Library. Select Manage Libraries from the displayed sub menu.

The Library Manager will open in its own window.
In the Filter Your Search box type “tfmini”
The result should be the TFMini Library by Peter Jansen.
Click the More Info link. An Install button will appear.
Click the Install button to instal the library into your Arduino IDE.
You may now close the Library Manager.
Another library will be used with our demo sketch as well, this one is already installed by default into your Arduino IDE.  It’s the SoftwareSerial Library and it resolves a problem you’ll encounter using more than one serial device with your Arduino.

Your Arduino Uno has a single Hardware Serial port – an input (RX) on pin 0 and an output (TX) on pin 1. Internally these two pins are used in the USB interface that connects your Arduino to your computer.

Since the Uno only has one serial port you’ll run into problems using a device like the TF Mini LIDAR which itself requires a serial port. If you use pins 0 and 1 you won’t be able to use the Serial Monitor on the USB port, which creates a problem as that’s exactly what we want to do here.

The SoftwareSerial Library provides the solution. It allows you to use any two pins on an Arduino Uno as serial I/O pins and it handles the serial encoding and decoding of the data.
It’s not perfect and will not perform as well as a hardware serial port but it will certainly work with our sketch.

The sketch itself is included with the TF Mini Library. To use it open the File menu and select Examples. Scroll down the list of examples to the section labeled “Examples from Other Libraries”. Look for TF Mini and expand it. You’ll see two example sketches.

One example is called SingleReading. This is actually a “skeleton sketch”, by itself it doesn’t accomplish much but it is full of comments to where you would add your own code. You can use this as the basis for a design based upon the TF Mini.

The example we’ll be using is the other one, BasicReading. As its name suggests it takes basic readings from the TF Mini LIDAR sensor and displays the results on the serial monitor.
The sketch is reproduced here for your convenience.

/*
Example code for Benewake TFMini time-of-flight distance sensor. 
by Peter Jansen (December 11/2017)
This example code is in the public domain.
 
This example communicates to the TFMini using a SoftwareSerial port at 115200, 
while communicating the distance results through the default Arduino hardware
Serial debug port. 
 
SoftwareSerial for some boards can be unreliable at high speeds (such as 115200). 
The driver includes some limited error detection and automatic retries, that
means it can generally work with SoftwareSerial on (for example) an UNO without
the end-user noticing many communications glitches, as long as a constant refresh
rate is not required. 
 
The (UNO) circuit:
 * Uno RX is digital pin 10 (connect to TX of TF Mini)
 * Uno TX is digital pin 11 (connect to RX of TF Mini)
 
THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  
*/
 
#include <SoftwareSerial.h>
#include "TFMini.h"
 
// Setup software serial port 
SoftwareSerial mySerial(10, 11);      // Uno RX (TFMINI TX), Uno TX (TFMINI RX)
TFMini tfmini;
 
void setup() {
  // Step 1: Initialize hardware serial port (serial debug port)
  Serial.begin(115200);
  // wait for serial port to connect. Needed for native USB port only
  while (!Serial);
     
  Serial.println ("Initializing...");
 
  // Step 2: Initialize the data rate for the SoftwareSerial port
  mySerial.begin(TFMINI_BAUDRATE);
 
  // Step 3: Initialize the TF Mini sensor
  tfmini.begin(&mySerial);    
}
 
 
void loop() {
  // Take one TF Mini distance measurement
  uint16_t dist = tfmini.getDistance();
  uint16_t strength = tfmini.getRecentSignalStrength();
 
  // Display the measurement
  Serial.print(dist);
  Serial.print(" cm      sigstr: ");
  Serial.println(strength);
 
  // Wait some short time before taking the next measurement
  delay(25);  
}

The sketch starts by loading the TF Mini and SoftwareSerial libraries.  After that the SoftwareSerial port is setup as an object called “mySerial” using pins 10 and 11 as receive and transmit respectively.

An object called “tfmini” is also created using the TF Mini library.

In the setup the hardware (USB) serial port is setup. Note that this is set to a speed of 115,200 bps whoichis probably faster than your Arduino IDE serial monitor is currently setup. When you first run the sketch you’ll need to change the speed on the serial monitor to match.

The SoftwareSerial setup is next. The constant it uses for baud rate is derived from the TF Mini library.

Final step in the setup is to initialize the TF Mini sensor itself.

In the loop things are actually pretty simple. A couple of 16 bit integers are defined and assigned to the value of the hTF Mini distance and signal strength readings.  Then these values are displayed on the serial monitor. Once that is done a brief delay is set and the loop begins again.

Testing the TF Mini LIDAR with Arduino

After you have everything loaded and hooked up open your Serial Monitor in the Arduino IDE. If you are greeted with a bunch of gibberish make sure that the baud rate is set to 115,200 bps, this can be adjusted using the dropdown box on the bottom of the serial monitor. You may need to reset the Arduino after changing baud rate.

Once you get the serial monitor working you should be greeted by a display of distance and signal strength. Pick up the TF Mini LIDAR sensor and point it at a distant object while observing these readings.

Remember that the TF Mini LIDAR sensor has a minimum range of 30 cm , which is about a foot. Any objects closer than that wil register as being at 30 cm.

While this is a pretty simple sketch it does illustrate how easy it is to work with the TF Mini LIDAR sensor. One thing you’ll note is how quickly you get data back, especially if you compare it to the experiments we did using the HC-SR04 Ultrasonic Sensor. It shows how quickly a light-based position sensing system is compared to one based upon sound.

Now let’s move onto the next sensor, the RPLIDAR.

Working with the RPLIDAR

The RPLIDAR is a device that is capable of providing a lot of data so any project working with it needs to be able to quickly process that data and put it to use. If your application is something as sophisticated as a self-driving vehicle that’s a lot of computing power you’re going to need.

While it would be great to just slap this device on top of a robot car platform, hook it up to a arduino and go for a ride it really isn’t as easy as that. So we will have to begin with some simple experiments and work forward from there.

What we will do today is to look at the RPLIDAR device connections to understand how to hook it up to either an Arduino or to a computer using the serial interface. We’ll run an example from the SDK (Software Development Kit) available for the RPLIDAR and then we’ll see an Arduino code example.

So let’s begin.

RPLIDAR Connections

The RPLIDAR device has a 7-pin connector as illustrated here.

The pin functions are as follows:
  • GND – The Ground Connection.
  • RXD – Receive Data. This is a 5 volt TTL level pin.
  • TXD – Transmit Data. This is also a 5 volt TTL level pin.
  • VCC – 5 Volt power for the RD LIDAR electronics and Laser.
  • GND – Another Ground connection.
  • MOTOCTL – Motor Control input. A 5 volt PWM signal is applied here to control the motor speed.
  • VMOTO – Motor power supply. The motor requires 5 volts.
A small cable has been provided to use with the serial to USB adapter included with the RPLIDAR. This cable can also be used along with a 7-pin male header to connect the RPLIDAR to a solderless breadboard.

RP-LIDAR Software

Developing software and applications to use with the RPLIDAR has been made a lot easier thanks to an SDK (Software Development Kit) and some pretty good documentation. You can find links here to the latest RPLIDAR SDK and Documentation.

The SDK will allow you to use your computer to control the RPLIDAR device which is connected and powered using the serial to USB adapter and a USB cable.  The adapter has a microUSB connector so that’s the type of cable you’ll need, likely the same one you use to charge your phone will work.

Once you have downloaded and unzipped the SDK you are ready to use it on your computer. The software is available for all three platforms (Windows, Mac and LINUX) and on Windows you’ll also need to install a driver, which I will describe in a moment.

Another thing to note. One application, a demo app which is probably the”coolest” application, is only available on the Windows platform.  Keep that in mind if you are choosing a computer to use with the RPLIDAR SDK.

Windows Driver

If you are running the SDK on a Windows computer you will need to install a USB driver to communicate with the RPLIDAR device.  You’ll find the driver included with the SDK, there are versions for both 32 and 64 bit Windows systems.

Open the SDK folder that you unzipped and you should see two folders – sdk and tools. The tools folder actually contains everything you’ll need for using the RPLIDAR with Windows.

Inside the tools folder there are two other folders. The driver you need is in the cp2102_driver folder, so open that now.

The cp2102_driver folder contains a ZIP file. Unzip it and you’ll create another folder called CP210x_Windows_Drivers.  Open that folder and look for two application files:

  • CP210xVCPInstaller_x64.exe – This is the 64-bit Windows driver install program.
  • CP210xVCPInstaller_x86.exe – This is the 32-bit Windows driver install program.

Select the program suitable for your computer, for most modern computers you’ll want to use the 64-bit drivers for improved performance. If you are not sure what type of Windows you have look in the Settings Panel (Windows 10) then System and then About. Look at System Type to see if you have a 64 or 32-bit operating system.

RPLIDAR SDK Applications

There are some applications included with the SDK, one of them will only run in the Windows environment while the others can be run from the command lines of all three operating systems.

The applications are as follows:

  • Ultra Simple
  • Simple Grabber
  • Frame Grabber (Windows only)

Detailed information for working with these applications can be found in the SDK Handbook, you’ll find a link to the latest version of it on the  RPLIDAR SDK and Documentation page.

Running the applications on LINUX and OS X requires you to use the terminal or console to get at the command prompt. On Windows you will need the command prompt for the first two applications while the Frame Grabber is an application that has its own GUI. The documentation has details for the build process you’ll need to perform for LINUX and OS X.

The Ultra Simple Application

The Ultra Simple application is just basically a “framework” application. You can use this as a starting point for building your own applications for the RPLIDAR.

The application demonstrates the simplest way to connect to the RPLIDAR device and how to continuously scan and fetch data. The data is output to the console but of course in your own application you can modify this to use the data for your own requirements.

To run the application connect the RPLIDAR to the computer via the serial to USB adapter and a microUSB cable. Then run the application as follows from your command prompt:

  • Windows – ultra_simple <com_port>
  • Mac OS X – ultra_simple <usb tty device>
  • LINUX – ultra_simple <tty device>

If all is working you will see LIDAR data being updated to your console screen.

The Simple Grabber Application
The Simple Grabber is the next step up from the Ultra Simple Grabber, which makes sense! It does the following:
Gets the RPLIDAR serial number and firmware version.
Gets the RPLIDAR health status.
Grabs two rounds of scan data and displays it in a histogram.

You can run it as follows:

  • Windows – simple_grabber <com_port>
  • Mac OS X – simple_grabber <usb tty device>
  • LINUX – simple_grabber <tty device>

When it runs you should see device information followed by the histogram.

  • The Frame Grabber Application (Windows Only)
  • The Frame Grabber is the star of the show, unfortunately it only runs under Windows. It is the only one of the applications that uses a GUI.
  • The Frame Grabber continuously sweeps the room and displays a dynamic map of the points it scans. You can set the scan rate using controls on the GUI


To run the Frame Grabber do the following:

Hook up the RPLIDAR to your Windows computer using the serial to USB converter and a microUSB cable.  You should observe the RPLIDAR spinning once it is connected, this is normal.

Run the Frame Grabber application from the win32 folder (in the tools folder in the SDK).

You will be prompted to select a serial port. The one that has been selected for you should work. If it doesn’t make sure you installed the driver as per the earlier steps.

The GUI will open. Press the Start Scan button (the one highlighted in the above image) and the scan will begin.

You should observe the scan on the GUI screen, it can be maximized for best effect.

You can click the Stop button to stop the scan.

Explore the GUI, there are settings that you can change and it’s fun to change them while comparing scan results.  The application works best in a large room.

Using the RPLIDAR with Arduino

The RPLIDAR can also be used with a microcontroller like the Arduino (or a microcomputer like the Raspberry Pi).  We will see how to hook it up to an Arduino now.

The example sketch that we are going to run is included in the library that we will be installing to interface with the RPLIDAR.  It’s a simple but fun example and the only other components you’ll need are an RGB LED and three dropping resistors.

So let’s get started!

RPLIDAR Arduino Hookup

Here is how I have wired the RPLIDAR up to an Arduino.

A few items to make note of in this arrangement.

The RGB LED is a Common Anode type, as opposed to the somewhat more popular Common Cathode variety. Make sure you note that.

I used 150 ohm dropping resistors, any value around that should work.

The chart shows the connections to the transmit, receive and motor control pins on the RPLIDAR.

If you have trouble finding a connector to fit the cable that DFRobot provides try using an upside-down 7-pin Dupont male header strip. It connects well, you use the “short” end to connect to the cable and then can plug in the long end into a solderless breadboard.

Once you have this wired up you can run the sketch to make it work. Make sure that when you run it you have a bit of space around the RPLIDAR, this is another demo that works best in a larger room.

RPLIDAR Arduino Sketch

The sketch we are going to look at is a simple example that is included with the RPLIDAR Library.

The RPLIDAR Library is available on GitHub. The GitHub files can be downloaded individually or in a ZIP file, however you should note that the internal folder arrangement in the ZIP file is incorrect for installation into the Arduino IDE.

I have made a corrected version of this ZIP file which you can download here.

Once you have the library you’ll need to install in into your Arduino IDE. This process has been explained several times here before, essentially you open the Sketch menu from the menu bar and go to the Include Library sub-menu. At the top of the sub-menu you’ll see a selection to Add Zip Library. Select it and use the dialog box to navigate to the location you saved the (corrected) ZIP file with the RPLIDAR Library.

Once you select the file click OK to install the library.

Now that the RPLIDAR Library is installed you can load an example sketch.

Click on the File menu and gpo down to Examples. A sub menu will appear with many example sketch entries. Scroll down to TFMini (in Examples from Libraries) and select Distance to Color.

/*
 * RoboPeak RPLIDAR Arduino Example
 * This example shows how to control an RGB led based on the scan data of the RPLIDAR
 * 
 * The RGB led will change its hue based on the direction of the closet object RPLIDAR has been detected.
 * Also, the light intensity changes according to the object distance.
 *
 * USAGE:
 * ---------------------------------
 * 1. Download this sketch code to your Arduino board
 * 2. Connect the RPLIDAR's serial port (RX/TX/GND) to your Arduino board (Pin 0 and Pin1)
 * 3. Connect the RPLIDAR's motor ctrl pin to the Arduino board pin 3 
 * 4. Connect an RGB LED to your Arduino board, with the Red led to pin 9, Blue led to pin 10, Green led to pin 11
 * 5. Connect the required power supplies.
 * 6. RPLIDAR will start rotating when the skecth code has successfully detected it.
 * 7. Remove objects within the 0.5 meters' radius circule range of the RPLIDAR
 * 8. Place some object inside the 0.5 meters' range, check what will happen to the RGB led :)
 */
 
/* 
 * Copyright (c) 2014, RoboPeak 
 * All rights reserved.
 * RoboPeak.com
 *
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, 
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, 
 *    this list of conditions and the following disclaimer in the documentation 
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
 * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
 
// This sketch code is based on the RPLIDAR driver library provided by RoboPeak
#include <RPLidar.h>
 
// You need to create an driver instance 
RPLidar lidar;
 
// Change the pin mapping based on your needs.
/////////////////////////////////////////////////////////////////////////////
#define LED_ENABLE  12 // The GPIO pin for the RGB led's common lead. 
                       // assumes a common positive type LED is used
#define LED_R       9  // The PWM pin for drive the Red LED
#define LED_G       11 // The PWM pin for drive the Green LED
#define LED_B       10 // The PWM pin for drive the Blue LED
 
#define RPLIDAR_MOTOR 3 // The PWM pin for control the speed of RPLIDAR's motor.
                        // This pin should connected with the RPLIDAR's MOTOCTRL signal 
//////////////////////////////////////////////////////////////////////////////
                        
                        
 
#define NEO_RGBSPACE_MAX (byte)(200L*255/360)
int _r, _g, _b;
 
//Set current RGB with the hue: HSV(hue, x, x)
void hue_to_rgb( _u8 hue)
{
/*`
    Hue(in Degree):  0 (RED) ----> 60 (Yello) ----> 120 (Green) --...... ----> 360
    Hue'(fit to _u8):0       ----> 60/360*255 ----> 120/260*255 --...... ----> 255
*/
    
    //convert HSV(hue,1,1) color space to RGB space
    if (hue < 120L*255/360)   //R->G
    {
        _g = hue;
        _r = NEO_RGBSPACE_MAX - hue;
        _b = 0;
    }else if (hue < 240L*255/360)  //G->B
    {
        hue -= 120L*255/360;
        _b = hue;
        _g = NEO_RGBSPACE_MAX - hue;
        _r = 0;
    }else //B->R
    {
        hue -= 240L*255/360;
        _r = hue;
        _b = NEO_RGBSPACE_MAX - _r;
        _g = 0;
    }
}
 
void displayColor(float angle, float distance)
{
    //1. map 0-350 deg to 0-255
    byte hue = angle*255/360;
    hue_to_rgb(hue);
    
    //2. control the light 
    
    int lightFactor = (distance>500.0)?0:(255-distance*255/500);
    _r *=lightFactor;
    _g *=lightFactor;
    _b *=lightFactor;
    
    _r /= 255;
    _g /= 255;
    _b /= 255;    
    
    analogWrite(LED_R, 255-_r);
    analogWrite(LED_G, 255-_g);
    analogWrite(LED_B, 255-_b);   
}
 
void setup() {
  // bind the RPLIDAR driver to the arduino hardware serial
  lidar.begin(Serial);
  
  // set pin modes
  pinMode(RPLIDAR_MOTOR, OUTPUT);
  
  pinMode(LED_ENABLE, OUTPUT);
  pinMode(LED_R, OUTPUT);
  pinMode(LED_G, OUTPUT);
  pinMode(LED_B, OUTPUT);
  
  digitalWrite(LED_ENABLE, HIGH);
  
  analogWrite(LED_R,255);
  analogWrite(LED_G,255);
  analogWrite(LED_B,255);
}
 
float minDistance = 100000;
float angleAtMinDist = 0;
 
void loop() {
  if (IS_OK(lidar.waitPoint())) {
    //perform data processing here... 
    float distance = lidar.getCurrentPoint().distance;
    float angle = lidar.getCurrentPoint().angle;
    
    if (lidar.getCurrentPoint().startBit) {
      // a new scan, display the previous data...
       displayColor(angleAtMinDist, minDistance);
       minDistance = 100000;
       angleAtMinDist = 0;
    } else {
       if ( distance > 0 &&  distance < minDistance) {
          minDistance = distance;
          angleAtMinDist = angle;
       }
    }
  } else {
    analogWrite(RPLIDAR_MOTOR, 0); //stop the rplidar motor
    
    // try to detect RPLIDAR... 
    rplidar_response_device_info_t info;
    if (IS_OK(lidar.getDeviceInfo(info, 100))) {
       //detected...
       lidar.startScan();
       analogWrite(RPLIDAR_MOTOR, 255);
       delay(1000);
    }
  }
}

The Distance to Color Sketch scans the room using the RPLIDAR and displays the output data as a color on the RGB LED. Distance and angle values are translated into color hues. It makes for a very interesting display!

It begins by including the RPLidar Library and then defining an object using that library.

Next the connections to the common anode RGB LED are defined. Note that the common anode is not connected to 5 volts as you might expect but instead is connected to Arduino I/O pin 12. This allows the I/O pin to be used as an enable line for the LED.

The displayColor function translates angle and distance values into colors. It is used along with the hue_to_rgb function.

In the setup the RPLIDAR device is initialized and the pinModes are set for the RGB LED and RPLIDAR motor pins.

In the loop we see if the RPLIDAR is available and sending data, if it isn’t we initialize it and attempt to get data from it.

Assuming the RPLIDAR is running we look at the scan data we are receiving. There are two possible things we’ll find out:

  • This is the beginning of a new scan, therefore no data has yet been obtained.
  • This is the middle of a scan and the dat we are getting is valid
  • If it is a new scan we just display the previous data values through the RGB LED. If it is in the middle of the scan we get the positional data and send it to the displayColor function to drive the LED in the color specified for that distance and angle.

Testing the TF RPLIDAR with Arduino

As I’ve mentioned you’ll need a large area to test, remember that the minimum distance the RPLIDAR detects is 30 cm or about a foot.  If you can keep objects at least a meter (a yard) from the RPLIDAR you’ll achieve good results.

Also, you’ll want to mount or fasten the RPLIDAR unit itself in a way where nothing obstructs its view. I used a “3rd Hand” adapter in the video as a temporary mount, you can probably come up with something suitable if you look around your workshop.

Now as the sketch is using pins 0 and 1 on the Arduino it would conflict with the USB port, so you can’t use this sketch while monitoring on your computer. You can use the USB port to power the Arduino or use an external power source.

Once you have it all arranged fire it up and observe the LED. Now try placing objects within the detection range, noting the color of the LED. Move the objects around the RPLIDAR unit, as you travel the full 360 degrees you should see drastic changes in the LED color.

All in all it’s a fun sketch!

Going Further with LIDAR

As you can see we have barely scratched the surface of the potential that these two LIDAR devices have. The fact that DFRobot has them for such a low price makes LIDAR available to the masses now and that is sure to spawn some amazing projects.

I have a couple of projects in mind for both units.

For the TF Mini LIDAR I’ve already assembled a pan and tilt mechanism so that I can mount the LIDAR sensor to it and use it to create a “point cloud” of the area ahead of the sensor. This will be a start to a sophisticated robotic project I’ve got planned for the near future.

As for the RPLIDAR an obvious use is for navigation and mapping in a small robot. Fort the same sophisticated robot project I would like a robot to be able to “learn” its surroundings so that it can make its own decisions when navigating through a room. This LIDAR unit is a great way to accomplish that.

In conclusion I’d like to thank the people at DFRobot for providing these wonderful sensors. They have a great selection of robotics parts and I’d urge you to check out their website and take a look.
Now let’s get scanning!


Resources

TF Mini LIDAR at DFRobot – The TF Mini stationary LIDAR device at DFRobot.
RPLIDAR at DFRobot – The RPLIDAR 360 degree scanning LIDAR at DFRobot.