Hook a 2D LiDAR to Raspberry Pi and use lds2d (Python)
All Guides
dev
diy
maker

Hook a 2D LiDAR to Raspberry Pi and use lds2d (Python)

- Hook a 2D LiDAR to Raspberry Pi and use lds2d (Python)

June 05, 2026·6 min. read
  • Hook a 2D LiDAR to Raspberry Pi and use lds2d (Python)
  • Quick guide: Raspberry Pi + 2D LiDAR with lds2d library
  • Cheap 2D LiDAR on Raspberry Pi — wiring, code, tradeoffs

Summary

This guide shows how to connect a 2D scanning LiDAR to a Raspberry Pi and use a small Python library (lds2d) you wrote to read scans. Advantages/examples:

  • Low-cost mobile robotics: obstacle detection and mapping with a Pi.
  • Simple data pipeline: serial/USB LiDAR → lds2d → your app (visualizer, ROS bridge, logger).
  • Fast prototyping: minimal wiring and a compact Python API for scans.

You'll get wiring notes, install steps, a minimal example program, filtering/calibration tips, alternatives and tradeoffs, parts list, and common pitfalls.

Parts / tools (minimalist)

  • Raspberry Pi 3/4 (Linux image with Python 3)
  • 2D spinning LiDAR module (TTL/serial or USB interface)
  • USB-to-serial adapter (if LiDAR uses UART)
  • Stable power supply (Pi + LiDAR; use separate supply if LiDAR needs >500 mA or different voltage)
  • Jumper wires, soldering iron (optional), multimeter
  • microSD card, SSH/keyboard for Pi

Safety and first checks

  • Read the LiDAR datasheet: required supply voltage/current and signal levels (TTL vs RS232 vs USB).
  • Never power a 12 V LiDAR from the Pi 5 V rail. Use a dedicated regulator/supply.
  • Check logic levels: Pi UART is 3.3 V TTL. If LiDAR is 5 V TTL, use a level shifter.

Wiring (typical)

  1. If LiDAR has USB: plug it into Pi USB port. It will show as /dev/ttyUSB0 or /dev/ttyACM0.
  2. If LiDAR has UART (TX/RX/GND/VCC):
  • Connect LiDAR GND to Pi GND.
  • If voltage and current allow, LiDAR VCC to appropriate supply (not always Pi 5V).
  • Connect LiDAR TX → Pi RX (GPIO15, /dev/serial0) through a level shifter if LiDAR uses >3.3V TTL.
  • Connect LiDAR RX → Pi TX if the LiDAR expects Pi to send commands.
  • If using USB-to-serial adapter: connect LiDAR TX/RX to adapter RX/TX and plug adapter into Pi USB.

Software prerequisites on Pi

Open a terminal on the Pi and run:

sudo apt update
sudo apt install python3-pip python3-venv git

Enable and configure serial port if using /dev/serial0:

sudo raspi-config
# Interface Options → Serial, disable shell over serial, enable serial port hardware

Add your user to dialout:

sudo usermod -a -G dialout $USER

Reboot or re-login.

Install lds2d and dependencies

If you published the library to PyPI:

python3 -m pip install --user lds2d

If local or from Git:

git clone <your-lds2d-repo-url>
cd lds2d
python3 -m pip install --user .

Also ensure pyserial (or any required backends) installed:

python3 -m pip install --user pyserial numpy

(Adjust commands if your library uses a different name or includes extras.)

Minimal example using lds2d

Below is a minimal usage pattern. Replace device path and API calls to match your lds2d API if names differ.

from lds2d import Lidar  # example import; adjust to your library

DEVICE = "/dev/ttyUSB0"  # or /dev/serial0, /dev/ttyACM0

def main():
lidar = Lidar(DEVICE, baudrate=115200)  # pass params your library needs
try:
lidar.start()  # or open() depending on API
while True:
scan = lidar.get_scan()  # e.g., returns list of (angle_deg, distance_m)
# simple filtering
valid = [(a, d) for a, d in scan if d and d > 0.01]
# print a few points
print(len(valid), "points; sample:", valid[:5])
except KeyboardInterrupt:
pass
finally:
lidar.stop()  # or close()

if __name__ == "__main__":
main()

If lds2d yields raw packets, add a conversion step (angles, distance units). Keep reads non-blocking if you combine with other IO.

Simple visualization (optional)

For quick debugging, plot points in Matplotlib:

import matplotlib.pyplot as plt
angles, dists = zip(*valid)
x = [r * math.cos(math.radians(a)) for a, r in valid]
y = [r * math.sin(math.radians(a)) for a, r in valid]
plt.scatter(x, y, s=2)
plt.axis('equal')
plt.pause(0.01)
plt.clf()

This is slow for real-time; use OpenGL/pygame for faster rendering.

Filtering and calibration

  • Remove zero or NaN distances returned by some sensors.
  • Median filter per angle bin to reduce spurious spikes.
  • Ignore readings beyond max_range reported by your sensor or those obviously noisy.
  • If angles are jittery, accumulate several rotations and average points by angle bin.
  • Time-stamp scans if integrating with odometry.

Alternatives and trade‑offs

  • USB LiDAR vs UART: USB is easiest (no level shifting), while UART gives lower-level control and sometimes lower latency.
  • Cheap spinning 2D LiDARs: good for hobby SLAM and obstacle avoidance — limited range and angular resolution compared to industrial units.
  • Time-of-Flight modules (single-point) are cheaper but not suitable for 2D scanning.
  • 2D vs 3D: 2D is sufficient for ground robots and mapping floors; 3D is heavier, more expensive, and more data to process.
  • Power: high-performance LiDARs may need separate regulated supplies; low-cost models often run on 5 V but check current draw.

I slightly prefer USB modules for prototyping because they minimize wiring and driver issues; switch to TTL/UART for embedded builds where you need a more compact connection.

Tips, pitfalls, gotchas

  • Tip: Always verify which /dev/tty* the LiDAR appears as after plug-in (dmesg or ls /dev).
  • Pitfall: Wiring TX/RX backwards is common — TX of sensor → RX of Pi.
  • Gotcha: Some sensors stream continuously; opening serial without stopping the stream can produce garbled output. Use library-provided start/stop.
  • Tip: Use a separate power supply for LiDAR if uncertain about current draw; check for voltage dips on Pi.
  • Gotcha: Remember to set correct baudrate and parity — wrong settings produce garbage.

Debugging checklist

  • Use a serial monitor (miniterm or screen) to confirm raw packets:
python3 -m serial.tools.miniterm /dev/ttyUSB0 115200
  • Check dmesg on connect to verify the device node.
  • Use a logic-level tester/multimeter to confirm voltage levels on TX/RX, VCC, and GND.

Next steps

  • Hook lds2d output into a SLAM library (RTAB-Map, Cartographer) or ROS node for mapping.
  • Add timestamped frames and integrate odometry for better localization.
  • Implement a driver that publishes scans as ROS sensor_msgs/LaserScan if needed.

This guide gives a clear path from wiring to working scans. Keep your wiring tidy, respect power requirements, and filter raw data before using it in mapping or navigation.

Parts & Tools