Your first robot programming course
You can start programming robots with a normal computer. You do not need to buy a humanoid, own a GPU or train a neural network. This course begins with a small Python program, progresses to a simulated motor and then introduces the tools used for motion, sensing and communication. Every exercise has a specific output to check.
By the end, you will be able to send a joint target, record the joint response, solve the geometry of a two-joint arm, calculate the trajectory of a biped foot and send a velocity message to a simulated mobile robot. The exercises cover different layers of a robotics system rather than assuming that one program controls every kind of robot.
| Tool | What you will use it for | When to install it |
|---|---|---|
| Python 3 | Variables, loops, mathematics, control programs | First |
| VS Code or a plain text editor | Edit and save .py files; run in a terminal | First |
| MuJoCo | Simulate articulated joints, actuators and physical state | After basic Python |
| Matplotlib | Plot a trajectory or recorded data | Optional |
| ROS 2 Jazzy | Exchange messages between separate robot programs | After simulation |
| Arduino IDE and Servo library | Program an optional small hardware demonstration | After simulation |
Lesson 1: install Python and write your first command
Install a supported 64-bit Python 3 interpreter. On Windows open PowerShell or the VS Code terminal; on Linux and macOS open a normal shell. Create a folder named robot-course and use that folder for every downloaded Python script. On Windows use py -3 if python is not recognized. On Linux or macOS, python3 may be the correct command.
mkdir robot-course
cd robot-course
python --versionOpen the robot-course folder in your editor. Create a file named first_steps.py and type the following program. Do not paste the Python statements directly into PowerShell. Save the file, then ask Python to execute it.
import math
# A robot joint target may be written in radians.
targets_deg = [0, 15, 30, 15, 0]
for angle_deg in targets_deg:
if not -45 <= angle_deg <= 45:
raise ValueError("Target outside the exercise range")
angle_rad = math.radians(angle_deg)
print(f"{angle_deg:3d} deg -> {angle_rad:.3f} rad")Download first_steps.py and save it in your robot-course folder.
python first_steps.py 0 deg -> 0.000 rad
15 deg -> 0.262 rad
30 deg -> 0.524 rad
15 deg -> 0.262 rad
0 deg -> 0.000 radUnderstand what the program does
- targets_deg is a list of five target angles in degrees.
- The for loop reads one target at a time.
- The if statement refuses a target outside the exercise range. These are example bounds, not safe limits for physical hardware.
- math.radians converts degrees to radians, a common robotics unit.
- print displays the requested angles. This program does not yet move a virtual or physical motor.
Try replacing 30 with 40 and observe the new value. Then enter 60: the program should stop with ValueError. You have just implemented a simple target check before sending a command.
Start with a measurable movement
Program a single simulated hinge to reach a requested angle. This keeps the first exercise small enough to inspect. You will define the mechanism, set a target, advance time and read the resulting position. There is no walking policy to train and no physical robot to purchase.
MuJoCo provides a CPU physics engine with Python bindings. Its interactive renderer and its GPU simulation backends are separate pieces. The exercise below uses no viewer, camera rendering, MJX or CUDA. A supported Python environment is enough to attempt this small CPU simulation; performance on a particular computer still depends on that machine. [2]
Lesson 2: understand the robot control loop
A controller compares a requested position with an observed position. For a position-controlled motor, the difference is the position error; velocity feedback can reduce oscillation. In a simulator the joint state comes from a physics calculation. In hardware, feedback can come from an encoder.
| Variable | Meaning in the MuJoCo exercise | Unit |
|---|---|---|
| q* / ctrl[0] | Requested angle | radians |
| q / qpos[0] | Measured simulated angle | radians |
| qvel[0] | Angular velocity | rad/s |
| q* - q | Position error | radians |
| dt | One numerical simulation step | seconds |
The position actuator in the preserved hinge example uses proportional gain kp and velocity gain kv. A larger gain can change the response but does not make every mechanism safer or more stable. Record the motion rather than assuming the final target was reached.
Create an isolated Python environment
Make a folder for the exercise and run the following command in its terminal. Use a Python interpreter supported by the current MuJoCo package. The official Python documentation for MuJoCo explains that its pip package includes the simulation library. [1]
python -m venv robot-labOn Linux or macOS, install into that environment with robot-lab/bin/python -m pip install mujoco. On Windows, use robot-lab\Scripts\python.exe -m pip install mujoco. Keep the interpreter path when running the exercise so installation and execution use the same environment.
Check your development environment before running MuJoCo
After creating the virtual environment described above, use its interpreter in every MuJoCo exercise. The following commands install the package and verify the import without starting a graphical window. Run only the command pair for your operating system.
Windows (PowerShell)
.\robot-lab\Scripts\python.exe -m pip install mujoco
.\robot-lab\Scripts\python.exe -c "import mujoco; print(mujoco.__version__)"Linux and macOS
./robot-lab/bin/python -m pip install mujoco
./robot-lab/bin/python -c "import mujoco; print(mujoco.__version__)"A version number confirms that the package imports in this environment. A ModuleNotFoundError means that the interpreter you used does not have MuJoCo installed. Resolve that before running the simulation. If pip cannot find a compatible distribution, check the Python version and supported platform. [1]
Move a hinge to half a radian
Save this original exercise as one_joint.py. The XML defines a half-kilogram capsule on a vertical hinge and a position actuator. Its target is 0.5 radians. The actuator applies feedback as the simulated joint moves. The timestep is 0.002 seconds, so 1,000 steps cover two seconds of simulated time. [3]
import mujoco
scene = """
<mujoco model="one_joint">
<option timestep="0.002" integrator="implicitfast"/>
<worldbody>
<body>
<joint name="turn" type="hinge" axis="0 0 1" damping="0.1"/>
<geom type="capsule" fromto="0 0 0 0.3 0 0" size="0.03" mass="0.5"/>
</body>
</worldbody>
<actuator>
<position joint="turn" kp="5" kv="0.5"/>
</actuator>
</mujoco>
"""
model = mujoco.MjModel.from_xml_string(scene)
state = mujoco.MjData(model)
state.ctrl[0] = 0.5
for step in range(1000):
mujoco.mj_step(model, state)
print(f"time={state.time:.2f}s angle={state.qpos[0]:.3f}rad")Run robot-lab/bin/python one_joint.py on Linux or macOS, or robot-lab\Scripts\python.exe one_joint.py on Windows. Here state.ctrl[0] holds the requested angle, while state.qpos[0] holds the simulated joint angle. Each mj_step call advances the simulated state by the configured timestep. The program should print time=2.00s angle=0.500rad. [1] [2]
After the hinge exercise, inspect the 29-actuator G1 model. The next tutorial records joint and sensor data from a floating humanoid model.
Change one parameter at a time
- Change the target to 0.2 radians and rerun from the initial state.
- Print the angle every 100 steps to see the path to the target.
- Reduce the actuator gain and compare how long the joint takes to settle.
- Keep a table of target, final angle, gain and timestep.
The controller responds to the difference between the target and measured angle. The position gain sets its response to that error, while the velocity gain damps the motion. Studying that error is more informative than checking that a script exited. This exercise has one fixed-base joint and no contact task, perception or balancing. A humanoid adds those coupled problems.
Lesson 3: program a sequence of joint movements
Instead of sending one fixed angle, send three targets at successive times: 0.5 rad, -0.4 rad and zero. The example contains its own MuJoCo scene and position actuator, so you do not need to download a robot model. The simulated hinge has a mechanical range and the actuator restricts its command range. These limits are for this exercise only.
import csv
import math
import mujoco
SCENE = """
<mujoco model="beginner_hinge">
<compiler angle="degree"/>
<option timestep="0.002" integrator="implicitfast"/>
<worldbody>
<light pos="0 0 2"/>
<body pos="0 0 0.4">
<joint name="turn" type="hinge" axis="0 0 1"
range="-60 60" damping="0.1"/>
<geom type="capsule" fromto="0 0 0 0.3 0 0"
size="0.03" mass="0.5" rgba="0.1 0.5 0.7 1"/>
</body>
<geom type="plane" size="1 1 0.05" rgba="0.7 0.7 0.7 1"/>
</worldbody>
<actuator>
<position name="turn_motor" joint="turn" kp="5" kv="0.5"
ctrllimited="true" ctrlrange="-0.8 0.8"/>
</actuator>
</mujoco>
"""
def make_robot():
model = mujoco.MjModel.from_xml_string(SCENE)
return model, mujoco.MjData(model)
def target_at(t):
if t < 2.0:
return 0.5
if t < 4.0:
return -0.4
return 0.0
def main():
model, data = make_robot()
dt = model.opt.timestep
with open("joint_trace.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["time_s", "target_rad", "angle_rad", "error_rad"])
for step in range(3000):
target = target_at(step * dt)
data.ctrl[0] = target
mujoco.mj_step(model, data)
angle = data.qpos[0]
if step % 50 == 0 or (step + 1) % 1000 == 0:
writer.writerow([data.time, target, angle, target - angle])
if (step + 1) % 1000 == 0:
print(f"t={data.time:.1f}s target={target:.2f} "
f"angle={angle:.3f} error={target-angle:.4f}")
assert math.isfinite(angle)
print("Saved joint_trace.csv")
if __name__ == "__main__":
main()Download joint_motion.py and save it in your robot-course folder.
.\robot-lab\Scripts\python.exe joint_motion.py./robot-lab/bin/python joint_motion.pyThe script runs 3,000 physics steps at 0.002 seconds per step. Every two simulated seconds it prints the target, measured angle and error. It also saves joint_trace.csv. Open that CSV in a spreadsheet to plot angle_rad and target_rad against time_s.
t=2.0s target=0.50 angle=0.500 error=0.0000
t=4.0s target=-0.40 angle=-0.400 error=-0.0000
t=6.0s target=0.00 angle=-0.000 error=0.0000How to modify the sequence
- Change the values returned by target_at() to define intermediate poses. Keep them inside the simulated actuator range.
- Change the time thresholds to alter the duration at each target.
- Read the angle from data.qpos[0], rather than using data.ctrl[0] as the measured result.
- Inspect the logged error. If motion oscillates, compare a lower position gain and suitable damping before changing several parameters at once.
Lesson 4: see your robot moving in MuJoCo
The earlier exercises run headlessly. To watch the capsule rotate, save view_joint.py beside joint_motion.py. It imports the same model and target generator so the visual motion and logged exercise use the same definitions. The passive viewer is synchronized after each physics step and the loop is paced toward real time. The window closes after six simulated seconds or when you close it. [1]
import time
import mujoco
import mujoco.viewer
from joint_motion import make_robot, target_at
model, data = make_robot()
with mujoco.viewer.launch_passive(model, data) as viewer:
while viewer.is_running() and data.time < 6.0:
start = time.monotonic()
data.ctrl[0] = target_at(data.time)
mujoco.mj_step(model, data)
viewer.sync()
remaining = model.opt.timestep - (time.monotonic() - start)
if remaining > 0:
time.sleep(remaining)Download view_joint.py and save it in your robot-course folder.
.\robot-lab\Scripts\python.exe view_joint.py./robot-lab/bin/python view_joint.py./robot-lab/bin/mjpython view_joint.pyIf the viewer cannot initialize its graphics context, run joint_motion.py without the window to continue the course and check the platform graphics requirements. This is a schematic model of a motor-driven link, not a representation of a commercial robot.
Lesson 5: program a robotic arm with two joints
A robot arm often receives a requested tool position rather than two angle values. Inverse kinematics converts that position into joint angles. Forward kinematics performs the opposite calculation. Start with two links in a plane: the first rotates at the shoulder and the second rotates relative to the first at the elbow.
This exercise uses lengths of 0.25 m and 0.20 m and a target at x = 0.30 m and y = 0.20 m. It selects one elbow configuration using acos and verifies the result with forward kinematics. An unreachable target raises an exception.
import math
def solve(x, y, l1, l2):
"""Planar 2R inverse kinematics, one elbow branch, radians."""
if l1 <= 0 or l2 <= 0:
raise ValueError("Link lengths must be positive")
r = math.hypot(x, y)
if not abs(l1 - l2) <= r <= l1 + l2:
raise ValueError("Target outside geometric workspace")
if r < 1e-9:
raise ValueError("Target at singular origin")
c2 = (x*x + y*y - l1*l1 - l2*l2) / (2*l1*l2)
q2 = math.acos(max(-1.0, min(1.0, c2)))
q1 = math.atan2(y, x) - math.atan2(
l2 * math.sin(q2), l1 + l2 * math.cos(q2))
return q1, q2
def forward(q1, q2, l1, l2):
return (l1*math.cos(q1) + l2*math.cos(q1+q2),
l1*math.sin(q1) + l2*math.sin(q1+q2))
if __name__ == "__main__":
target = (0.30, 0.20)
lengths = (0.25, 0.20)
q1, q2 = solve(*target, *lengths)
reached = forward(q1, q2, *lengths)
print(f"Shoulder: {math.degrees(q1):.2f} deg")
print(f"Elbow: {math.degrees(q2):.2f} deg")
print(f"Calculated tip: ({reached[0]:.3f}, {reached[1]:.3f}) m")
assert math.dist(target, reached) < 1e-9Download two_link_ik.py and save it in your robot-course folder.
python two_link_ik.pyIn the execution check, the shoulder printed 1.46 degrees, the elbow 74.04 degrees and the calculated tip (0.300, 0.200) m. Change the target to (0.25, 0.10) and compare the two joint angles. Try (0.60, 0.0): it lies outside the maximum geometric reach of this example.
Lesson 6: calculate a humanoid robot’s first footstep
A walking controller needs more than joint angles. It must support the body, shift load onto the stance leg and coordinate the swing foot. We can nevertheless learn the first part of that problem without letting a real robot fall: calculate a swing-foot path relative to a fixed hip and solve the leg geometry for each sample.
In this educational model the two leg links are each 0.23 m. The foot begins 0.40 m below the hip. It travels 0.10 m forward and rises 0.06 m at mid-swing. A squared sine defines the lift profile; 101 samples describe the commanded path. Inverse kinematics turns those samples into hip and knee angle pairs.
import math
import csv
import sys
from two_link_ik import solve, forward
# Hip fixed at origin; z points up. A kinematic swing-foot
# exercise only. It does not simulate balance or contact.
l1 = l2 = 0.23
samples = []
for k in range(101):
u = k / 100
x = 0.10 * u
z = -0.40 + 0.06 * math.sin(math.pi * u)**2
q1, q2 = solve(x, z, l1, l2)
px, pz = forward(q1, q2, l1, l2)
assert math.hypot(px-x, pz-z) < 1e-9
samples.append((u, x, z, q1, q2))
with open("footstep.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["phase", "x_m", "z_m", "hip_rad", "knee_rad"])
writer.writerows(samples)
print("101 trajectory samples saved to footstep.csv")
print(f"Peak lift: {max(row[2] for row in samples)+0.40:.3f} m")
print(f"Step length: {samples[-1][1]:.3f} m")
if "--plot" in sys.argv:
import matplotlib.pyplot as plt
plt.plot([row[1] for row in samples],
[row[2] for row in samples], color="teal")
plt.axhline(-0.40, color="gray", linestyle="--", label="Ground")
plt.xlabel("Forward position (m)")
plt.ylabel("Vertical position (m)")
plt.axis("equal")
plt.legend()
plt.show()Download first_footstep.py and save it in your robot-course folder.
Keep two_link_ik.py from the previous lesson in the same folder. Both exercises use the standard Python library, except for the optional plotting feature.
python first_footstep.py101 trajectory samples saved to footstep.csv
Peak lift: 0.060 m
Step length: 0.100 mPlot the footstep
.\robot-lab\Scripts\python.exe -m pip install matplotlib
.\robot-lab\Scripts\python.exe first_footstep.py --plot./robot-lab/bin/python -m pip install matplotlib
./robot-lab/bin/python first_footstep.py --plotOpen footstep.csv to inspect the movement phase, forward position, vertical position and hip/knee targets. Change 0.10 to 0.08 for a shorter step. Check that each point remains within the geometric workspace. The angles are measured in the simple planar model, not in the coordinate conventions of a particular humanoid.
Continue with the Unitree G1 simulation tutorial for a model with more joints and sensor readings. This still does not give you a tested walking policy.
Add ROS 2 when programs need to communicate
ROS 2 introduces nodes, publishers and subscribers so separate parts of a robot system can exchange messages. Its DDS design documents explain the communication model. For a later version of this exercise, put the target generator and the state logger in separate nodes. Send the target in one topic and the measured position in another. [Source ↗]
Use the official ROS 2 documentation for the release installed on your computer. Complete its beginner node and topic material before combining a simulator, camera driver and controller. The documentation repository links to the maintained manuals. [Source ↗]
Lesson 7: program a robot with ROS 2 and turtlesim
A single Python script can run a small simulator. Larger systems use separate programs for cameras, navigation, controls and monitoring. ROS 2 provides a shared message system. A node sends commands using a publisher and receives messages using a subscriber. A topic identifies a stream of messages; its type defines the fields.
Use ROS 2 Jazzy on a supported Ubuntu 24.04 installation for these commands. Windows users can use a compatible Ubuntu environment with GUI support or a separate Linux computer. The next commands set up the official ROS package repository for Ubuntu Noble. Do not run apt commands in Windows PowerShell. If ROS 2 Jazzy is already installed, skip the repository and installation commands. [Source ↗]
sudo apt update
sudo apt install software-properties-common curl
sudo add-apt-repository universe
ROS_APT_SOURCE_VERSION=$(curl -fsSL https://api.github.com/repos/ros-infrastructure/ros-apt-source/releases/latest | python3 -c 'import json,sys; print(json.load(sys.stdin)["tag_name"])')
curl -fL -o /tmp/ros2-apt-source.deb "https://github.com/ros-infrastructure/ros-apt-source/releases/download/${ROS_APT_SOURCE_VERSION}/ros2-apt-source_${ROS_APT_SOURCE_VERSION}.noble_all.deb"
sudo dpkg -i /tmp/ros2-apt-source.deb
sudo apt update
sudo apt install ros-jazzy-desktop ros-jazzy-turtlesim
source /opt/ros/jazzy/setup.bashTerminal 1: start the simulator
source /opt/ros/jazzy/setup.bash
export ROS_DOMAIN_ID=42
ros2 run turtlesim turtlesim_nodeTerminal 2: discover and control the simulated robot
source /opt/ros/jazzy/setup.bash
export ROS_DOMAIN_ID=42
ros2 node list
ros2 topic list -t
ros2 run turtlesim turtle_teleop_keyA turtle window should appear. Use the arrow keys with the teleoperation terminal focused, then exit that node before using the following command. The velocity message has linear and angular components. Inspect the simulator topic names and read its reported pose. [Source ↗] [Source ↗]
ros2 topic echo /turtle1/pose --once
ros2 topic pub --once /turtle1/cmd_vel geometry_msgs/msg/Twist "{linear: {x: 1.0}, angular: {z: 0.6}}"Write a Python ROS 2 node
The next program publishes velocity commands for five seconds and subscribes to the turtle pose. With a forward speed and a nonzero angular speed, the simulated turtle draws a curved line. The routine waits for the simulator to respond and publishes a zero velocity when it finishes normally.
# ROS 2 Jazzy. Use with turtlesim only, never a physical robot.
import time
import rclpy
from geometry_msgs.msg import Twist
from turtlesim.msg import Pose
def main():
rclpy.init()
node = rclpy.create_node("beginner_circle")
pub = node.create_publisher(Twist, "/turtle1/cmd_vel", 10)
last_pose = None
def on_pose(msg):
nonlocal last_pose
last_pose = msg
sub = node.create_subscription(Pose, "/turtle1/pose", on_pose, 10)
try:
# Wait for the simulator to be discovered, up to 5 seconds.
deadline = time.monotonic() + 5
while rclpy.ok() and (pub.get_subscription_count() == 0 or last_pose is None):
if time.monotonic() >= deadline:
raise RuntimeError("Start turtlesim in the same ROS domain")
rclpy.spin_once(node, timeout_sec=0.1)
start = time.monotonic()
while rclpy.ok() and time.monotonic() - start < 5.0:
cmd = Twist()
cmd.linear.x = 1.0
cmd.angular.z = 0.6
pub.publish(cmd)
rclpy.spin_once(node, timeout_sec=0.05)
time.sleep(0.05)
if last_pose is not None:
print(f"x={last_pose.x:.2f}, y={last_pose.y:.2f}")
except KeyboardInterrupt:
pass
finally:
if rclpy.ok():
pub.publish(Twist())
rclpy.spin_once(node, timeout_sec=0.1)
node.destroy_subscription(sub)
node.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main()Download turtle_circle.py and save it in your robot-course folder.
source /opt/ros/jazzy/setup.bash
export ROS_DOMAIN_ID=42
python3 turtle_circle.pyUse the Ubuntu system Python that ROS 2 was built against, not the separate MuJoCo virtual environment. Start turtlesim first. Keep the same ROS domain in every terminal, and do not connect these exercises to a physical robot network. You can see the command path using rqt_graph if that tool is installed.
Lesson 8: optional first real motor with Arduino
Once you understand a target angle and a motion sequence, try a small hobby positional servo on a bench. Use a supported Arduino board such as an UNO, a compatible low-voltage positional servo, a regulated supply sized for that servo, a USB cable and jumper wires. No humanoid or heavy mechanism is required.
Connect the bench circuit with power off
- Connect the servo signal wire to Arduino digital pin 9, confirming the servo pinout using its datasheet.
- Connect servo power to an external regulated supply matching the servo voltage and current requirements. Do not assume all servos use the same voltage.
- Connect the supply ground, servo ground and Arduino GND so the signal has a common reference. Do not connect the external positive supply to the Arduino 5 V pin.
- Secure the unloaded servo on a stable surface. Remove horns or linkages that could strike anything. Verify wiring before supplying power.
Install Arduino IDE, select the board and serial port, and install the Arduino Servo library if it is absent. Open a new sketch named first_servo and paste this program. It centers a conventional positional servo, makes a small movement and returns to center. Verify that the selected servo permits these commands before powering it. [Source ↗]
#include <Servo.h>
Servo joint;
const int signalPin = 9;
void setup() {
joint.attach(signalPin);
joint.write(90);
delay(1000);
for (int angle = 90; angle <= 95; angle++) {
joint.write(angle);
delay(50);
}
for (int angle = 95; angle >= 85; angle--) {
joint.write(angle);
delay(50);
}
joint.write(90);
}
void loop() {
// No repeated movement.
}Download first_servo.ino and save it in your robot-course folder.
Press Verify to compile, then Upload. The servo should make one small sweep instead of moving continuously. Disconnect the servo supply if it binds, heats or moves unexpectedly. The angle commands are nominal: the physical angle depends on the servo and calibration.
What to do next: practice, diagnose and measure
| Symptom | Check first |
|---|---|
| Python cannot find a module | Run pip with the same interpreter that runs the script. |
| File not found | Check the current folder and exact file name. Download the companion files into the same folder. |
| No simulated movement | Verify the model has an actuator, assign the target and call mj_step repeatedly. |
| Robot motion is too fast | Inspect the simulated timestep and command trajectory; do not confuse simulation time with wall-clock time. |
| Inverse kinematics rejects a target | Check units, link lengths and the reachable workspace. |
| ROS 2 topic not found | Source the same ROS distribution in every terminal, start the simulator and compare ROS_DOMAIN_ID. |
| A physical servo heats or binds | Cut power and verify mechanical clearance, wiring and its rated supply before testing again. |
A useful next project is to build a small simulated arm with a gripper, reproduce a motion from a CSV file and then record the target versus measured angle. For a wheeled robot, extend the ROS exercise by stopping at a requested simulated position using pose feedback. For a biped, study balance and contact constraints after the footstep exercise. Keep the real robot disconnected until you have its manufacturer’s tested startup and safety procedures.
Choose an open-source robot with a documented build route when you are ready to investigate model-specific hardware, CAD and control software.
How to install the software mentioned on this page
Choose only the tools required for your project. The commands below describe development and simulation setup, not proof of compatibility with a specific physical robot. Match the versions in the original project and test offline before connecting hardware.
Python Windows, macOS, Linux
Install the Python release required by your robot or library. On Windows use the official installer; on Ubuntu use the distribution package. Create a separate virtual environment for each project.
Installation / setup commands
python -m venv .venv
# Windows PowerShell:
.\.venv\Scripts\Activate.ps1
# Linux or macOS:
source .venv/bin/activateVerify the installation
python --version
python -m pip --version
Official instructions: https://www.python.org/downloads/
MuJoCo Windows, macOS, Linux
Create a Python virtual environment and install the official Python package. On macOS use mjpython for the interactive viewer when required.
Installation / setup commands
python -m pip install mujocoVerify the installation
python -c "import mujoco; print(mujoco.__version__)"
Official instructions: https://mujoco.readthedocs.io/en/stable/python.html
ROS 2 (Jazzy example) Ubuntu 24.04 for Jazzy; other distributions have different instructions
On Ubuntu 24.04 first configure the official ROS apt repository using the documented ros2-apt-source procedure. Then install Jazzy desktop. Use the distribution required by your robot; for example Humble normally uses Ubuntu 22.04.
Installation / setup commands
sudo apt update
sudo apt install ros-jazzy-desktop
source /opt/ros/jazzy/setup.bashVerify the installation
ros2 --help
Official instructions: https://docs.ros.org/en/jazzy/Installation/Ubuntu-Install-Debs.html
NVIDIA CUDA Toolkit Supported NVIDIA GPU and OS
Choose a CUDA Toolkit release matching the project, compatible driver and PyTorch build. Use NVIDIA's platform installer steps. A system-wide CUDA installation is not always needed for prebuilt PyTorch wheels.
Verify the installation
nvidia-smi
nvcc --version
Official instructions: https://developer.nvidia.com/cuda-downloads
VS Code Windows, macOS, Linux
Install Visual Studio Code from Microsoft, then install only the language extensions your project needs (Python or C/C++). Open the project folder and select its own Python environment.
Verify the installation
code --version
Official instructions: https://code.visualstudio.com/download
Arduino IDE Windows, macOS, Linux
Download Arduino IDE from Arduino, install it, and use Boards Manager to install the board package specified by the project. Install only required libraries. Do not upload firmware until the board model and wiring are confirmed.
Verify the installation
Open the IDE and confirm the target board is listed.
Official instructions: https://www.arduino.cc/en/software
Matplotlib Python environment on a supported OS
Use the Python version supported by the project.
Installation / setup commands
python -m pip install matplotlibVerify the installation
python -c "import matplotlib; print('Import OK')"
Official instructions: https://matplotlib.org/stable/install/index.html
MuJoCo MJX Supported Python environment
Install the matching MuJoCo package and backend for your project; use the documented Warp extra only for that backend.
Installation / setup commands
python -m pip install mujoco-mjxVerify the installation
python -c "import mujoco.mjx; print('Import OK')"
Official instructions: https://mujoco.readthedocs.io/en/stable/mjx.html
Ubuntu PC / virtual machine
Choose the Ubuntu release supported by your robot SDK, ROS or simulator. Download the official ISO or use a supported virtual machine. Back up the computer before installing or changing partitions.
Verify the installation
lsb_release -a
Official instructions: https://ubuntu.com/download/desktop
Sources and verification
- MuJoCo Python bindingsGoogle DeepMind / MuJoCo · Read 8 October 2026
Official installation and MjModel, MjData and mj_step API documentation.
- MuJoCo engine overviewGoogle DeepMind / MuJoCo · Read 8 October 2026
Separates the CPU simulation engine, OpenGL rendering and GPU backends.
- MuJoCo MJCF referenceGoogle DeepMind / MuJoCo · Read 8 October 2026
Hinge joint, position actuator and integration settings used in the original exercise.
Article history
Explained the target, simulated joint angle and position and velocity gains used by the runnable one-joint exercise.
Added a contextual link to the simulation series for the next engineering step.
Expanded the guide into a progressive beginner course with downloadable code, three technical diagrams, simulation exercises, ROS 2 and an optional servo bench project. Preserved the original hinge exercise.