Implementation:CARLA simulator Carla ROS2 Native Example
| Knowledge Sources | |
|---|---|
| Domains | ROS Integration, Example Scripts |
| Last Updated | 2026-02-15 05:00 GMT |
Overview
A Python example script that demonstrates native ROS2 integration with CARLA by spawning a vehicle with sensors configured from a JSON file and publishing sensor data to ROS2 topics.
Description
This script sets up a CARLA simulation in synchronous mode (fixed 0.05s delta) with a vehicle and multiple sensors configured from a JSON configuration file. The _setup_vehicle(world, config) function spawns a vehicle using the blueprint type and sets both role_name and ros_name attributes from the config. The _setup_sensors(world, vehicle, sensors_config) function iterates over sensor definitions in the JSON, configures blueprint attributes, sets spawn transforms with CARLA-to-ROS coordinate conventions (negating y, pitch, and yaw), attaches sensors to the vehicle, and calls enable_for_ros() on each sensor to activate native ROS2 publishing. The main loop enables autopilot on the vehicle and ticks the world in synchronous mode. On shutdown, it restores original world settings and destroys all spawned actors. Command-line arguments specify host, port, JSON configuration file, and verbosity.
Usage
Use this script to quickly set up a CARLA vehicle with sensors publishing to ROS2 without a ROS bridge, leveraging CARLA's native ROS2 support for direct topic publishing.
Code Reference
Source Location
- Repository: CARLA
- File: PythonAPI/examples/ros2/ros2_native.py
Signature
def _setup_vehicle(world, config):
"""Spawn a vehicle from JSON config with ROS2 naming."""
def _setup_sensors(world, vehicle, sensors_config):
"""Spawn and configure sensors with ROS2 publishing enabled."""
def main(args):
"""Main loop: setup world, vehicle, sensors, and run simulation."""
Import
# Run as standalone script
python ros2_native.py -f vehicle_config.json
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| --host | str | No | CARLA server IP (default: localhost) |
| --port | int | No | CARLA server port (default: 2000) |
| -f, --file | str | Yes | JSON configuration file for vehicle and sensors |
| -v, --verbose | flag | No | Enable debug logging |
Outputs
| Name | Type | Description |
|---|---|---|
| ROS2 topics | Sensor data | Each sensor publishes natively to ROS2 topics |
| Vehicle behavior | Simulation | Autopilot-driven vehicle in synchronous simulation |
Usage Examples
# Run with a JSON config file
# python ros2_native.py -f sensors.json --host localhost --port 2000
# Example JSON config structure:
# {
# "type": "vehicle.lincoln.mkz_2017",
# "id": "ego_vehicle",
# "sensors": [
# {
# "type": "sensor.camera.rgb",
# "id": "front_camera",
# "spawn_point": {"x": 2.0, "y": 0.0, "z": 1.4, "roll": 0, "pitch": 0, "yaw": 0},
# "attributes": {"image_size_x": "800", "image_size_y": "600"}
# }
# ]
# }