Author: LvDaengineer
Project: quadruped-robot
License: MIT
A 12-DOF quadruped robot simulation and control framework. This project provides two independent simulation environments:
| Simulation | Engine | Control | Platform |
|---|---|---|---|
| Part I | CoppeliaSim (V-REP) | MATLAB via Legacy Remote API | Windows / Linux |
| Part II | Gazebo Classic 11 + ROS 2 Humble | Python (rclpy) | Linux (Ubuntu 22.04) |
Both simulations implement analytical inverse kinematics, gait generation, and trajectory planning for a quadruped robot with four 3-DOF legs.
- Repository Structure
- Branch Strategy
- Part I — CoppeliaSim + MATLAB Simulation
- Part II — Gazebo + ROS 2 Simulation
- II.1 Overview
- II.2 Prerequisites
- II.3 Installing ROS 2 Humble
- II.4 Installing Gazebo Classic 11
- II.5 Installing Additional ROS 2 Dependencies
- II.6 Clone the Repository
- II.7 Project Structure (ROS 2)
- II.8 Building the Workspace
- II.9 Running the Simulation
- II.10 Publishing Gait Commands
- II.11 Expected Behavior
- II.12 Common Errors and Solutions
- Contributing
- Contact
This simulation uses MATLAB as the control engine and CoppeliaSim (formerly V-REP) as the physics simulator. MATLAB computes joint angles via inverse kinematics and gait planning algorithms, then sends real-time commands to CoppeliaSim through the Legacy Remote API (TCP, port 19999).
Key features:
- Analytical forward and inverse kinematics for 3-DOF leg configurations
- Gait generation with cubic trajectory planning
- Navigation module with SLAM (lidarSLAM) and Augmented Kalman Filter (AKF)
- Synchronous simulation loop for deterministic execution
| Software | Version | Purpose |
|---|---|---|
| MATLAB | R2023a or later | Control logic, kinematics, trajectory planning |
| CoppeliaSim Edu | 4.6.0 (recommended) | Physics simulation engine |
| Robotics Toolbox for MATLAB | Latest | Robot model visualization (Peter Corke) |
| C Compiler (MinGW / GCC) | Latest | Required to load the Remote API library in MATLAB |
- Download the CoppeliaSim Edu installer from the official website:
https://www.coppeliarobotics.com/downloads - Select the appropriate version: CoppeliaSim Edu, V4.6.0 rev18, Windows 64-bit.
- Run the
.exeinstaller and follow the on-screen instructions. - Choose an installation directory (e.g.,
C:\Program Files\CoppeliaRobotics\CoppeliaSimEdu). - After installation, verify by launching
coppeliaSim.exefrom the installation folder. - Ensure the Remote API server is enabled:
- Open CoppeliaSim.
- Go to Tools > User settings and confirm that the Remote API is set to listen on port
19999. - Alternatively, a child script in the simulation scene can start the server automatically.
- Download the Linux tarball from:
https://www.coppeliarobotics.com/downloads - Select: CoppeliaSim Edu, V4.6.0 rev18, Ubuntu 22.04, 64-bit.
- Extract the archive:
cd ~/Downloads tar -xf CoppeliaSim_Edu_V4_6_0_rev18_Ubuntu22_04.tar.xz mv CoppeliaSim_Edu_V4_6_0_rev18_Ubuntu22_04 ~/CoppeliaSim
- Install required system libraries:
sudo apt update sudo apt install -y libgl1-mesa-dev libxkbcommon-x11-0 libxcb-xinerama0
- Launch CoppeliaSim:
cd ~/CoppeliaSim ./coppeliaSim.sh
- If you encounter a
libQt5error, install the Qt5 dependencies:sudo apt install -y qt5-default libqt5opengl5-dev
- Download MATLAB from the MathWorks website:
https://www.mathworks.com/products/matlab.html - Install MATLAB R2023a or later with the following toolboxes:
- Robotics System Toolbox (or install Peter Corke's Robotics Toolbox via MATLAB Add-On Explorer)
- Navigation Toolbox (required for
lidarSLAM)
- Install a C compiler for MEX files:
- Windows: Install MinGW-w64 via MATLAB Add-On Explorer (search "MATLAB Support for MinGW-w64 C/C++ Compiler").
- Linux: GCC is typically pre-installed. Verify with:
gcc --version
- Configure MATLAB to use the compiler:
mex -setup
git clone https://github.com/longvotheengineer/quadruped-robot.git
cd quadruped-robot
git checkout developNote: The
developbranch is the default and contains the latest stable code. Themainbranch is reserved for releases.
All MATLAB simulation files are located under Simulation/MATLAB/MotionControl/:
Simulation/
├── CoppeliaSim/
│ ├── RobotDog3.ttt # Main robot scene file
│ └── Navigation.ttt # Navigation/SLAM scene file
└── MATLAB/
└── MotionControl/
├── main.m # Entry point — connects to CoppeliaSim and runs the control loop
├── setup.m # Adds all subfolders to the MATLAB path
├── MotionControl/
│ ├── ForwardKinematics.m # FK solver
│ ├── InverseKinematics.m # IK solver (analytical, geometric decomposition)
│ ├── Gait.m # Gait trajectory waypoint generator
│ ├── controlGait.m # Gait execution controller
│ ├── controlPath.m # Path-level control orchestrator
│ └── cubicPlanning.m # Cubic polynomial trajectory planning
├── RemoteAPI/
│ ├── remApi.m # MATLAB wrapper for the CoppeliaSim Remote API
│ ├── remoteApiProto.m # Function signature prototypes
│ └── remoteApi.dll # Windows DLL (replace with .so for Linux)
├── Navigation/
│ ├── AKF.m # Augmented Kalman Filter
│ ├── AStar.m # A* path planning
│ └── ... # SLAM and sensor processing utilities
└── UnitSimulation/
├── test.m # Quick kinematics test
├── testControlGait.m # Gait controller test
├── testTrajectory.m # Trajectory planning test
└── ... # Additional unit tests and visualization scripts
The Remote API library must match your operating system:
| OS | Library File | Location |
|---|---|---|
| Windows (64-bit) | remoteApi.dll |
Simulation/MATLAB/MotionControl/RemoteAPI/ |
| Linux (64-bit) | remoteApi.so |
Must be copied from CoppeliaSim installation |
For Linux users: Copy the shared library from your CoppeliaSim installation:
cp ~/CoppeliaSim/programming/remoteApiBindings/lib/lib/Ubuntu22_04/remoteApi.so \
Simulation/MATLAB/MotionControl/RemoteAPI/Important: The library architecture (64-bit) must match your MATLAB architecture. Run
computer('arch')in MATLAB to verify.
- Launch CoppeliaSim.
- Open the scene file: File > Open Scene and navigate to:
Simulation/CoppeliaSim/RobotDog3.ttt - Verify the scene contains the quadruped robot model with 12 revolute joints.
- Ensure the Remote API child script is attached to an object in the scene.
- Open MATLAB.
- Navigate to
Simulation/MATLAB/MotionControl/. - Run the setup script to add all subfolders to the path:
setup()
- Start the simulation in CoppeliaSim by clicking the Play button (or pressing
Ctrl+Shift+P). The Remote API server will start listening on port19999. - Run the main script in MATLAB:
main - MATLAB will attempt to connect to CoppeliaSim at
127.0.0.1:19999. If successful, you will see:Connected to remote API server - The control loop will begin executing, sending joint commands to the simulation.
To test individual modules without CoppeliaSim:
cd UnitSimulation
% Test kinematics
test
% Test gait controller
testControlGait
% Test trajectory planning
testTrajectory- The robot in CoppeliaSim should begin moving its legs according to the gait pattern.
- The MATLAB console will display
Connected to remote API serverfollowed by continuous control loop output. - If the Navigation scene (
Navigation.ttt) is used, a MATLAB figure window will show the SLAM map with the robot position overlay.
Cause: CoppeliaSim is not running or the Remote API server is not started.
Solution:
- Ensure CoppeliaSim is open and the scene is loaded.
- Press the Play button in CoppeliaSim before running
main.m. - Verify the port by checking the CoppeliaSim status bar for
Remote API server started on port 19999.
Cause: No compatible C compiler is configured, or the library architecture does not match.
Solution:
- Install a C compiler (MinGW on Windows, GCC on Linux).
- Run
mex -setupin MATLAB and select the installed compiler. - Verify the library matches MATLAB's architecture:
computer('arch')should returnwin64orglnxa64.
Cause: The MATLAB path does not include the RemoteAPI folder.
Solution: Run the setup script:
setup()Or manually add the path:
addpath('RemoteAPI')Cause: 32-bit DLL loaded in 64-bit MATLAB (or vice versa).
Solution:
Download the correct architecture version of remoteApi.dll from the CoppeliaSim installation:
<CoppeliaSim>/programming/remoteApiBindings/lib/lib/
Cause: The Navigation Toolbox is not installed.
Solution: Install via MATLAB Add-On Explorer or the command:
matlab.addons.install('Navigation Toolbox')Cause: The simulation is not in synchronous mode, or the child script is missing.
Solution:
- Verify the scene contains a child script that starts the Remote API server.
- Ensure
sim.simxSynchronous(clientID, true)is called inmain.m(it is by default). - Restart both CoppeliaSim and MATLAB, then run again.
This simulation uses ROS 2 Humble with Gazebo Classic 11 for physics simulation. The robot is defined via a URDF model and controlled through the ros2_control framework with effort-based joint controllers. A Python-based gait generator (leg_controller package) computes joint trajectories and publishes commands to the Gazebo virtual motors.
Key features:
- URDF model with 12 revolute joints (4 legs, 3 DOF each)
ros2_controlintegration viagazebo_ros2_controlpluginJointGroupEffortControllerfor torque-level controlJointStateBroadcasterfor encoder feedback- RViz2 visualization with custom configuration
- Custom Gazebo world with tuned physics for legged locomotion
- Gait generation with quintic polynomial trajectory planning
- Command interface via ROS 2 topic (
/gait_control)
| Software | Version | Purpose |
|---|---|---|
| Ubuntu | 22.04 LTS (Jammy Jellyfish) | Operating system |
| ROS 2 | Humble Hawksbill | Middleware framework |
| Gazebo Classic | 11 | Physics simulation |
| Python | 3.10 | Node development |
| colcon | Latest | Build tool |
Important: This simulation is designed for Linux only (Ubuntu 22.04). WSL2 on Windows is not officially supported due to GPU passthrough requirements for Gazebo rendering.
Follow the official ROS 2 Humble installation guide for Ubuntu 22.04. The complete steps are reproduced below.
locale # check for UTF-8
sudo apt update && sudo apt install locales
sudo locale-gen en_US en_US.UTF-8
sudo update-locale LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8
export LANG=en_US.UTF-8
locale # verify settingssudo apt install software-properties-common
sudo add-apt-repository universesudo apt update && sudo apt install curl -y
sudo curl -sSL https://raw.githubusercontent.com/ros/rosdistro/master/ros.key -o /usr/share/keyrings/ros-archive-keyring.gpgecho "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/ros-archive-keyring.gpg] http://packages.ros.org/ros2/ubuntu $(. /etc/os-release && echo $UBUNTU_CODENAME) main" | sudo tee /etc/apt/sources.list.d/ros2.list > /dev/nullsudo apt update
sudo apt upgrade -y
sudo apt install ros-humble-desktop -ysource /opt/ros/humble/setup.bashTo make this permanent, add it to your shell configuration:
echo "source /opt/ros/humble/setup.bash" >> ~/.bashrc
source ~/.bashrcsudo apt install ros-dev-tools -y
sudo apt install python3-colcon-common-extensions -yOpen two terminals:
Terminal 1 (Talker):
source /opt/ros/humble/setup.bash
ros2 run demo_nodes_cpp talkerTerminal 2 (Listener):
source /opt/ros/humble/setup.bash
ros2 run demo_nodes_py listenerYou should see the listener printing "Hello World" messages from the talker.
Gazebo Classic 11 is typically installed with ros-humble-desktop. Verify the installation:
gazebo --versionExpected output: Gazebo multi-robot simulator, version 11.x.x
If not installed, install manually:
sudo apt install gazebo -y
sudo apt install libgazebo-dev -yThe following ROS 2 packages are required by this project:
sudo apt install -y \
ros-humble-gazebo-ros-pkgs \
ros-humble-gazebo-ros2-control \
ros-humble-ros2-control \
ros-humble-ros2-controllers \
ros-humble-joint-state-publisher-gui \
ros-humble-robot-state-publisher \
ros-humble-xacro \
ros-humble-rviz2Verify the key packages:
ros2 pkg list | grep gazebo_ros2_control
ros2 pkg list | grep ros2_controllersBoth commands should return the package names. If they do not, re-run the installation step above.
mkdir -p ~/catkin_ws/src
cd ~/catkin_ws/src
git clone https://github.com/longvotheengineer/quadruped-robot.git
cd quadruped-robot
git checkout developNote: The
developbranch contains the latest simulation code. Themainbranch is reserved for stable releases.
The ROS 2 workspace is located at Software/Middleware/robot_ros2/:
Software/Middleware/robot_ros2/
├── src/
│ ├── launch_main/ # Top-level launch package
│ │ ├── launch/
│ │ │ ├── launch_sim.py # Launch simulation environment
│ │ │ └── launch_real.py # Launch real-hardware environment
│ │ ├── CMakeLists.txt
│ │ └── package.xml
│ │
│ ├── simulation/ # Simulation description package
│ │ ├── urdf/
│ │ │ └── quadruped_robot.urdf # Robot URDF model (12 joints, ros2_control)
│ │ ├── launch/
│ │ │ └── launch_simulation.py # Simulation launch (Gazebo, RViz, controllers)
│ │ ├── config/
│ │ │ └── ros2_gazebo_controller.yaml # ros2_control controller configuration
│ │ ├── worlds/
│ │ │ └── custom_physics.world # Gazebo world with tuned friction and physics
│ │ ├── rviz/
│ │ │ └── config.rviz # RViz visualization configuration
│ │ ├── meshes/ # 3D mesh files for visualization
│ │ ├── sim_imu_controller/ # Simulated IMU controller
│ │ ├── setup.py
│ │ └── package.xml
│ │
│ ├── leg_controller/ # Gait control package
│ │ ├── leg_controller/
│ │ │ ├── nodeLegController.py # Main ROS 2 node (entry point)
│ │ │ ├── nodeWebGui.py # Web GUI for real-time control
│ │ │ ├── gaitController.py # Gait pattern execution
│ │ │ ├── gaitGenerator.py # Gait pattern generator
│ │ │ ├── gaitTrajectory.py # Trajectory planning module
│ │ │ ├── gaitConfig.py # Gait parameters and configuration
│ │ │ ├── gaitBalance.py # IMU-based balance compensation
│ │ │ ├── kinematics.py # Inverse kinematics solver
│ │ │ ├── quinticPlanning.py # Quintic polynomial trajectory planning
│ │ │ ├── actuator.py # Hardware actuator interface
│ │ │ └── controllerSim.py # Gazebo joint state subscriber and publisher
│ │ ├── setup.py
│ │ └── package.xml
│ │
│ ├── balance_controller/ # PID balance controller
│ │ └── balance_controller/
│ │ └── nodeBalanceController.py
│ │
│ ├── serial_driver/ # Hardware serial comm (C++)
│ │ ├── src/
│ │ │ ├── serial_driver.cpp # Main serial communication driver
│ │ │ ├── servo_calibrator.cpp # Standalone calibrator utility
│ │ │ └── calibrate_limits.cpp # Joint limits configuration
│ │ ├── calibration/ # Scripts for initial hardware setup
│ │ │ ├── test_servo_phase0.cpp
│ │ │ ├── calibrate_servo.cpp
│ │ │ └── change_servo_id.cpp
│ │ └── SCServo_Linux/ # SCS/STS servo SDK
│ │
│ ├── paper/ # IEEE-style research paper (LaTeX)
│ └── thesis/ # Capstone thesis document (LaTeX)
│
├── build/ # colcon build output (auto-generated)
├── install/ # colcon install output (auto-generated)
└── log/ # colcon log output (auto-generated)
cd ~/catkin_ws/src/quadruped-robot/Software/Middleware/robot_ros2source /opt/ros/humble/setup.bashcolcon build --symlink-installNote: The
--symlink-installflag creates symbolic links instead of copies, allowing you to edit Python files without rebuilding.
source install/setup.bashImportant: You must source the workspace overlay in every new terminal that needs to use these packages. Consider adding this to your shell configuration:
echo "source ~/catkin_ws/src/quadruped-robot/Software/Middleware/robot_ros2/install/setup.bash" >> ~/.bashrc
You can run the full system either in the Gazebo simulation environment or on the real physical hardware. Both launch configurations automatically start the backend controllers and the interactive Web GUI.
Starts Gazebo, RViz, the simulated robot model, and the controller nodes.
source /opt/ros/humble/setup.bash
source install/setup.bash
ros2 launch launch_main launch_sim.pyStarts the serial drivers for the physical servos and the controller nodes without opening the physics simulator.
source /opt/ros/humble/setup.bash
source install/setup.bash
ros2 launch launch_main launch_real.pyWhenever you launch the system (either simulation or real), a local web server is hosted automatically.
- Open your web browser.
- Navigate to http://localhost:8080.
- Use the visual interface to trigger locomotion gaits, adjust speed, and command body postures in real-time.
Alternatively, you can send gait commands directly via the /gait_control topic from the terminal.
The command format is:
<COMMAND> <STEP_COUNT>
COMMAND— One of the predefined gait or body-motion identifiers listed below.STEP_COUNT— Number of complete gait cycles to execute. Set to0for continuous (infinite) execution.
Terminal 3:
# Trot forward continuously
ros2 topic pub --once /gait_control std_msgs/msg/String "{data: 'TROT_FORWARD 0'}"
# Walk forward for 5 gait cycles, then hold position
ros2 topic pub --once /gait_control std_msgs/msg/String "{data: 'WALK_FORWARD 5'}"
# Execute body sway oscillation continuously
ros2 topic pub --once /gait_control std_msgs/msg/String "{data: 'BODY_SWAY 0'}"
# Return to the zero (homing) position
ros2 topic pub --once /gait_control std_msgs/msg/String "{data: 'ZERO 0'}"The table below lists all supported gait commands. Each command combines a direction with a gait pattern (phase shift configuration) and a trajectory type.
| Command | Gait Pattern | Trajectory | Description |
|---|---|---|---|
TROT_FORWARD |
Trot (diagonal pairs) | D-shape foot path | Move forward in trot gait — diagonal legs swing simultaneously |
TROT_BACKWARD |
Trot (diagonal pairs) | D-shape foot path (reversed) | Move backward in trot gait |
WALK_FORWARD |
Walk (sequential) | D-shape foot path | Move forward in walk gait — legs swing one at a time in sequence |
WALK_BACKWARD |
Walk (sequential) | D-shape foot path (reversed) | Move backward in walk gait |
TURN_RIGHT |
Trot (diagonal pairs) | Left legs forward, right legs reversed | Rotate the body clockwise (turn right) |
TURN_LEFT |
Trot (diagonal pairs) | Right legs forward, left legs reversed | Rotate the body counter-clockwise (turn left) |
| Command | Phase Pattern | Trajectory | Description |
|---|---|---|---|
BODY_PUSHUP |
All legs in-phase | Vertical oscillation | All four legs extend and retract simultaneously — push-up motion |
BODY_SWAY |
Left/right pairs offset by 50% | Vertical oscillation | Body sways side-to-side — left and right legs oscillate in anti-phase |
BODY_CIRCLE |
Sequential 25% offset per leg | Vertical oscillation | Body traces a circular path — each leg is phase-shifted by 90 degrees |
| Command | Description |
|---|---|
ZERO |
Move all joints to the homing (zero) position via linear interpolation from current pose |
To inspect the current joint positions in real-time:
ros2 topic echo /joint_statesTo inspect the effort (torque) commands being sent to the virtual motors:
ros2 topic echo /leg_controller/commands- Gazebo Window: The quadruped robot appears in the custom world. The body is dark grey, hip links are red, upper legs are green, and lower legs are blue.
- RViz Window: The same robot model is visualized with TF frames displayed.
- Initial State: After the
node_leg_controllerstarts, the robot holds its initial standing pose. - After Gait Command: The robot begins executing the requested gait pattern. Legs move in coordinated pairs (trot gait), with trajectory following quintic polynomial profiles.
The balance and joint controllers have been tuned for optimal trajectory tracking and error minimization during various phases of operation. The following graphs demonstrate the PID error characteristics:
Left: Joint tracking error while maintaining the home position. Right: Joint tracking error during dynamic gait execution.
Cause: The gazebo_ros2_control package is not installed.
Solution:
sudo apt install ros-humble-gazebo-ros2-control -yCause: The ros2_control packages are not installed.
Solution:
sudo apt install ros-humble-ros2-control ros-humble-ros2-controllers -yCause: Newer versions of setuptools have deprecated the setup.py install method.
Solution:
pip install setuptools==58.2.0Then rebuild:
colcon build --symlink-installCause: The workspace overlay has not been sourced.
Solution:
source install/setup.bashCause: GPU driver issues or insufficient system resources.
Solution:
- Update your GPU drivers:
sudo ubuntu-drivers autoinstall sudo reboot
- If running in a virtual machine, try software rendering:
export LIBGL_ALWAYS_SOFTWARE=1 ros2 launch launch_main launch_main.py - Check system resources (minimum 4 GB RAM recommended):
free -h
Cause: The controller YAML configuration does not match the URDF ros2_control definition, or the gazebo_ros2_control plugin is not loaded.
Solution:
- Verify the URDF contains the
<gazebo>plugin block forlibgazebo_ros2_control.so. - Verify the YAML file (
ros2_gazebo_controller.yaml) lists all 12 joint names correctly. - Ensure the joint names in the YAML file exactly match those in the URDF (case-sensitive).
- Re-build and re-source:
colcon build --symlink-install source install/setup.bash
Cause: The URDF is missing collision or inertial properties, or the spawn height is incorrect.
Solution:
- All links in the URDF must have
<collision>and<inertial>elements. - Check the spawn position in
launch_simulation.py. The robot is spawned atz=0.4by default to account for leg length. - Verify the custom world file (
custom_physics.world) is loaded correctly.
Cause: The controller manager has not fully initialized when the spawner is invoked.
Solution: Add a delay before the spawner launches, or re-launch the system. The timing issue is intermittent and typically resolves on the second attempt:
ros2 launch launch_main launch_main.pyCause: The gazebo_ros2_control library is not in the Gazebo plugin path.
Solution:
- Set the plugin path explicitly:
export GAZEBO_PLUGIN_PATH=/opt/ros/humble/lib:$GAZEBO_PLUGIN_PATH
- Add this to your
~/.bashrcfor persistence:echo "export GAZEBO_PLUGIN_PATH=/opt/ros/humble/lib:\$GAZEBO_PLUGIN_PATH" >> ~/.bashrc source ~/.bashrc
Cause: A mismatch between the URDF and the ros2_control hardware interface.
Solution: This warning can be safely ignored when using gazebo_ros2_control with the <ros2_control> tag in the URDF (as this project does). The GazeboSystem plugin handles the hardware interface directly.
Contributions are welcome. Please follow these guidelines:
- Fork the repository and create a feature branch from
develop. - Follow the existing code style and naming conventions.
- Test your changes with both simulation environments before submitting a pull request.
- Open an issue first to discuss significant changes.
Author: LvDaengineer
Email: linhlong875@gmail.com
GitHub: longvotheengineer
Designed and developed by LvDaengineer


