On the screen, three robot arms pick strawberries in 3 seconds each and never touch. In the greenhouse, the first real arm arrives late and misses the fruit by 25 mm. The simulation did not lie about itself. It was never compared with the world. A simulation is a model, and a model that only agrees with itself proves nothing. This lesson builds a Python simulator for a two-joint arm from the kinematics, the Jacobian and the trajectories of this course, runs a harvesting cell of three arms in it, and shows how to check it: against a case solved by hand, and against one measurement on the machine. #RobotSimulation #PythonVisualization #AppliedRobotics
Learning Objectives
By the end of this lesson, you will be able to:
Build simulation framework combining FK, IK, Jacobian, and trajectory planning into one Python class
Animate robot motion using matplotlib FuncAnimation with real-time arm rendering and trajectory trails
Implement safety systems including joint limits, singularity avoidance, and workspace boundaries
Design multi-robot coordination for agricultural harvesting with collision-free task allocation
Apply robotics principles across manufacturing, logistics, medical, and agricultural domains
Real-World Engineering Challenge: Multi-Robot Agricultural Harvesting System
A farm wants to harvest ripe strawberries in a greenhouse row with three robot arms on a gantry, a rail above the row. Each arm is a 2R planar arm: two links joined by two revolute (turning) joints, a shoulder and an elbow, moving in one plane. A camera system gives the position of each ripe fruit. Each arm must reach a fruit, pick it, and place it in its collection bin, and no two arms may collide where their reach overlaps.
System Description
Three 2R planar arms at fixed bases along the gantry rail
A shared region where the reach of two neighboring arms overlaps
A vision system that gives the (x, y) position of each ripe fruit, in meters
A collection bin at the base of each arm
A cycle time target of 3 seconds per fruit (reach, pick, place, return)
The Simulation Challenge
Why Agricultural Robotics Is a Growing Field
Farms in many countries cannot find enough workers at harvest time. Strawberries are a hard case for a robot: the fruit is soft, partly hidden by leaves, and does not ripen all at once. A mistake on a real plant costs fruit, so the motion is tried in simulation first.
Consequences of Poor Simulation Design
A simulation finds some faults cheaply, before any hardware moves:
two arms that cross in the shared region
a pose near a singularity, where joint velocities become very large
one arm with most of the fruit while another waits
a target outside the reach of every arm
It cannot find a fault in something it does not contain. A simulator with no motor model shows an arm that moves at any speed. A simulator with a wrong link length reaches every target perfectly, in the wrong place.
Fundamental Theory
Simulation vs. Animation
A simulation calculates the state of the robot (joint angles, velocities, gripper position) at each time step from equations. An animation only draws pictures, one frame after another. In robotics the simulation comes first, and the animation draws what the simulation calculated. A smooth animation therefore says nothing about whether the equations behind it are right.
What it does: Calculates the state of the robot at each time step from the kinematic equations.
Key characteristics:
Stepped in time: the state at time follows from the state at
Based on equations: FK, IK, the Jacobian and the trajectory formulas of this course
Repeatable: the same inputs always give the same outputs
Checks limits: joint limits, singularities, the edge of the workspace
One time step: the new joint angles are the old angles plus the joint velocity multiplied by the time step.
Here is the list of joint angles (rad), is the list of joint velocities (rad/s), and is the time step (s).
What it does: Draws the robot at each frame from the simulation data.
Key characteristics:
Runs at a fixed display rate (for example 30 frames per second, FPS)
Draws only: it calculates no motion
May fill in between simulation steps for a smoother picture
Here it uses matplotlib FuncAnimation to draw a 2D arm
Animation loop:
Building a Robot Simulation Framework in Python
The simulator is one Python class that holds the model of the arm, its present state, the safety checks and the drawing. A class keeps these together, so that three arms are three copies of the same code.
State
It keeps the present joint angles , the joint velocities , and the position of the end-effector (the gripper at the tip of the arm).
Safety checks
It keeps each joint inside its limits , warns near a singular pose (), and refuses a target outside the workspace, the region the gripper can reach.
Drawing
It draws the arm, the trail of the gripper, the edge of the workspace and the safety zones with matplotlib.
Forward Kinematics
FK answers: with these joint angles, where is the gripper? The shoulder angle is measured from the x-axis. The elbow angle is measured from the direction of the first link. Add the reach of the first link to the reach of the second:
Check by hand. The arm of this lesson has m and m. Two poses need no calculator. Straight out along x (, ): the gripper must be at . Elbow bent at a right angle (, ): the first link lies along x and the second points up, so the gripper must be at . The formulas give and . Run these two poses through any FK code before you trust it.
Inverse Kinematics
IK answers the opposite question: to put the gripper at a target , which joint angles are needed? The law of cosines gives the elbow angle, and the shoulder angle follows:
The sign gives two answers, elbow up and elbow down, which reach the same point.
Jacobian Matrix
The Jacobian converts joint velocities to the velocity of the gripper, :
Its determinant is . It is zero when or (arm fully straight or fully folded). These poses are the singularities: the gripper cannot move along the line of the arm, whatever the joints do. The size of the determinant, , is called the manipulability. For this arm it is at most , at a right-angle elbow, and it falls to zero at a singularity.
Visualization with matplotlib
The matplotlib class FuncAnimation runs the animation. It calls an update function once per frame, and that function redraws the arm, the trail of the gripper and the edge of the workspace.
FuncAnimation Usage
The animation loop follows this structure:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots(figsize=(10, 10))
definit():
"""Set up the plot elements (called once)."""
ax.set_xlim(-3,3)
ax.set_ylim(-3,3)
ax.set_aspect('equal')
ax.grid(True,alpha=0.3)
return[]
defupdate(frame):
"""Update robot state and redraw (called every frame)."""
# 1. Advance simulation state
# 2. Compute FK for current joint angles
# 3. Redraw arm links and joints
# 4. Update trajectory trail
return[arm_line, joint_dots, trail_line]
anim =FuncAnimation(fig, update,init_func=init,
frames=num_frames,interval=33,blit=True)
plt.show()
Real-Time Arm Rendering
Each frame redraws the robot arm as connected line segments:
defdraw_arm(ax, theta1, theta2, L1, L2):
"""Draw 2R arm from base to end-effector."""
# Joint positions
x0, y0 =0.0, 0.0# base
x1 = L1 * np.cos(theta1)
y1 = L1 * np.sin(theta1)
x2 = x1 + L2 * np.cos(theta1 + theta2)
y2 = y1 + L2 * np.sin(theta1 + theta2)
# Draw links
arm_x =[x0, x1, x2]
arm_y =[y0, y1, y2]
arm_line.set_data(arm_x, arm_y)
# Draw joints as circles
joints.set_data([x0, x1, x2],[y0, y1, y2])
return x2, y2 # end-effector position
Trajectory Trails
Appending the end-effector position at each frame creates a trajectory trail:
trail_x, trail_y =[], []
defupdate_trail(ex, ey, max_points=200):
"""Add end-effector position to trail, trim to max length."""
trail_x.append(ex)
trail_y.append(ey)
iflen(trail_x) > max_points:
trail_x.pop(0)
trail_y.pop(0)
trail_line.set_data(trail_x, trail_y)
Workspace Overlay
The workspace of a 2R arm is a ring (an annulus). The gripper reaches no farther than from the base and no nearer than :
The class below is the whole simulator for one arm: FK, IK with the choice of elbow up or down, the Jacobian with a singularity warning, the cubic trajectory, and the joint limits. The harvesting cell later uses three copies of it. Note what it does not contain: no motor, no mass, no friction. An arm in this class moves as fast as the plan asks.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.patches import Circle
classRobot2R:
"""Complete 2R planar robot simulator.
Combines FK, IK, Jacobian, and trajectory planning from the
When you run this script, a matplotlib window opens showing:
Green dashed circle: the outer workspace boundary ( m)
Red dashed circle: the inner workspace boundary ( m)
Red triangle: the pick location
Blue square: the place location
Dark arm with red joints: the 2R robot arm moving through the pick-and-place sequence
Blue trail: the path traced by the end-effector
The arm starts at the home configuration, moves to the pick position, then to the place position, and returns home. Each segment starts and ends gently, because the cubic trajectory has zero velocity at both ends.
Each segment has 40 frames at 50 ms, so it lasts about 2 s. The largest joint move is the shoulder between pick and place, . A cubic has a peak velocity of 1.5 times the average, so the simulator asks that joint for deg/s. Whether a real motor can give that is a question the simulator does not ask.
ax.set_title('Workspace Manipulability Map with Safety Zones')
ax.legend(loc='upper right',fontsize=9)
ax.grid(True,alpha=0.2,color='white')
plt.tight_layout()
plt.show()
# Usage
robot =Robot2R(L1=1.0,L2=0.8)
visualize_workspace_safety(robot,resolution=150)
Practical Applications of Robotics
The same four tools serve every field below: FK to predict a position, IK to reach a target, the Jacobian to control velocity, and trajectory planning for motion the motors can make. Only the requirements change.
Manufacturing
Assembly Lines: Robots place components with sub-millimeter precision using IK to reach exact mounting positions and trajectory planning for repeatable cycle times.
Welding: Seam tracking requires real-time Jacobian-based velocity control to maintain consistent torch speed along curved weld paths.
Painting: Spray robots follow complex surface contours using task-space trajectory planning with orientation control (quaternions applied to 6-DOF arms).
Key metrics: cycle time, positioning repeatability, throughput
Logistics and Warehousing
Warehouse Sorting: Pick-and-place robots sort thousands of packages per hour, using IK to reach varying bin positions and cubic trajectories for gentle handling.
Palletizing: Stacking robots plan layer patterns and compute IK solutions for each placement position, adjusting for pallet height as layers build up.
Order Picking: Mobile manipulators combine navigation with arm kinematics to retrieve items from shelving, requiring workspace analysis for reach planning.
Key metrics: picks per hour, error rate, package damage rate
Medical Robotics
Surgical Systems (e.g., da Vinci): Teleoperated arms use Jacobian-based resolved-rate control so surgeons can command end-effector velocity in task space while the system computes joint velocities.
Rehabilitation: Exoskeleton robots guide patient limbs along therapeutic trajectories using joint-space interpolation with force limits for safety.
Pharmacy Automation: Dispensing robots use precise IK solutions to pick medications from storage bins and place them in patient trays with zero-error requirements.
Key metrics: positioning accuracy, force limits, safety redundancy
Agriculture
Harvesting: Robots identify ripe fruit with vision systems and use IK to reach each fruit position. Gentle cubic trajectories prevent bruising.
Planting: Seed placement robots compute IK for precise soil positions along pre-planned rows, maintaining consistent depth and spacing.
Crop Monitoring: Arms mounted on rovers extend sensors into crop canopies, using workspace analysis to determine which plants are reachable from each rover position.
Key metrics: harvest rate, fruit damage rate, field coverage
Food packaging, quality inspection and the 3D printing of buildings use the same tools.
Error Handling and Safety
A simulation must test four things at every time step: the joint limits, the distance from a singularity, the edge of the workspace, and collisions. In the simulation these tests stop impossible states. On a real arm the same tests prevent damage and injury.
Joint Limit Checking
Every joint has a range it can turn through. Beyond it, gears, belts or the motor can be damaged.
defenforce_joint_limits(q, limits):
"""Clamp angles and return violation flag."""
q_safe = q.copy()
violated =False
for i, (lo, hi) inenumerate(limits):
if q[i] < lo:
q_safe[i] = lo
violated =True
elif q[i] > hi:
q_safe[i] = hi
violated =True
return q_safe, violated
Singularity Avoidance
To move the gripper at a wanted velocity, the controller divides by . When is close to zero, a small gripper velocity asks for a very large joint velocity.
The damped least-squares method (also called Levenberg-Marquardt) adds a small positive number, , to the diagonal of the matrix before it is inverted. The sum can always be inverted, even exactly at a singularity, so the joint velocities stay limited.
The price is accuracy: near a singularity the gripper moves a little off the direction that was asked. In the code, the damping factor is zero away from a singularity and grows as the manipulability falls, so the error appears only where the protection is needed. The method was introduced in Velocity Kinematics and the Jacobian.
Workspace Boundary Enforcement
A target outside the ring of the workspace must be refused, or moved to the nearest point the arm can reach.
"""Project an out-of-workspace target onto the nearest reachable point."""
d = target - base
r = np.linalg.norm(d)
if r <1e-10:
# Target is at the base; project to inner boundary
return base + np.array([r_inner + margin, 0.0])
direction = d / r
if r > r_outer - margin:
return base + direction * (r_outer - margin)
elif r < r_inner + margin:
return base + direction * (r_inner + margin)
else:
return target # already inside workspace
Collision Detection Basics
With several arms, test whether any link of one arm crosses any link of another. Each link is treated as a straight line segment with no thickness, so a real cell needs a margin on top of this test.
defsegments_intersect(p1, p2, p3, p4):
"""Check if line segment (p1,p2) intersects segment (p3,p4).
Uses the cross-product orientation method.
"""
defcross2d(a, b):
return a[0] * b[1] - a[1] * b[0]
d1 = p2 - p1
d2 = p4 - p3
denom =cross2d(d1, d2)
ifabs(denom) <1e-10:
returnFalse# parallel segments
t =cross2d(p3 - p1, d2) / denom
u =cross2d(p3 - p1, d1) / denom
return0<= t <=1and0<= u <=1
defcheck_robot_collision(robot_a, robot_b):
"""Check if any links of two robots intersect."""
ee_a, elbow_a = robot_a.forward_kinematics()
ee_b, elbow_b = robot_b.forward_kinematics()
# Robot A segments: base->elbow, elbow->ee
seg_a =[(robot_a.base, elbow_a), (elbow_a, ee_a)]
# Robot B segments: base->elbow, elbow->ee
seg_b =[(robot_b.base, elbow_b), (elbow_b, ee_b)]
for (a1, a2) in seg_a:
for (b1, b2) in seg_b:
ifsegments_intersect(a1, a2, b1, b2):
returnTrue
returnFalse
System Application: Multi-Robot Agricultural Harvesting
Three 2R arms stand 2.0 m apart along the gantry. Each reaches 1.8 m, so the workspaces of neighbors overlap. The vision system gives a list of fruit positions. The simulation gives each fruit to an arm, plans the moves, tests every frame for a collision between arms, and animates the result.
Task Allocation Strategy
For each fruit, the program gives a score to every arm that can reach it: the manipulability at that point divided by the distance from the base of the arm. The fruit goes to the arm with the highest score. A near arm in a good pose wins. A fruit in the overlap between two arms goes to the one that reaches it more easily, and a fruit that no arm can reach is left out.
# Generate fruit positions (scattered in the harvesting zone)
np.random.seed(42)
num_fruit =12
fruit_x = np.random.uniform(-3.5,3.5, num_fruit)
fruit_y = np.random.uniform(0.5,1.8, num_fruit)
fruit_positions =[np.array([fx, fy]) for fx, fy inzip(fruit_x, fruit_y)]
# Create and run harvesting cell
cell =HarvestingCell()
cell.animate(fruit_positions)
What the simulation shows
The animation shows three arms (red, green, blue) along a horizontal gantry. Red dots in the upper half are strawberries. The colored squares below the bases are the collection bins.
Each arm reaches for a fruit, picks it, places it in the bin and returns home before the next fruit. The trails show the path of each gripper. The status line shows the frame number, the number of fruit given to each arm, and a warning if two arms cross.
With the seed 42, the arms receive 4, 2 and 5 fruit. That is 11 of the 12. The fruit near is 1.81 m from the nearest base, just beyond the 1.8 m reach, and the program leaves it out without a message. No frame reports a collision. That result holds for this set of fruit only: the program detects a collision but does nothing to avoid one.
Change the fruit_positions or the spacing of the arms and run it again. Put a fruit in the overlap between two arms to see which arm the score chooses.
Design Guidelines for Building Stable Simulations
Separate Simulation from Visualization
Let the simulation produce the trajectory (a list of joint angles) first, and let the animation only play it. Then you can save the trajectory, draw it another way, or run many cases with no drawing at all.
Always Check Feasibility Before Planning
Before you plan a move to a target, confirm three things: the target is inside the workspace, IK has an answer inside the joint limits, and the pose is not near a singularity. Then check the peak joint velocity of the planned move against the motor.
Use Smooth Trajectory Profiles
A cubic or quintic polynomial starts and stops at zero velocity, which spares the gears and the motor. Where segments join, the velocity must not jump. Never command a sudden step in a joint angle.
Implement Collision Checking for Multi-Robot
Where arms share space, test every link of each arm against every link of the others at every time step. Real cells use tested libraries for this: FCL (Flexible Collision Library, used by MoveIt), Bullet (used by Gazebo and PyBullet) and ODE. They handle real link shapes and many obstacles far better than code written by hand.
Scale Simulations Incrementally
Start with one arm and one pick-and-place, and check it by hand. Add a second arm and test the collision check. Only then run the full cell. A fault in a cell of three arms is much harder to find than a fault in one arm.
Bridging to Real Robots
The simulator of this lesson treats the arm as ideal: exact link lengths, joints that go where they are told, motors with no limit. A real arm is none of these.
The Sim-to-Real Gap
A real motor has friction, and a top speed. Gearboxes have backlash, a small free play of some tenths of a degree when the direction reverses. A load bends the arm by millimeters. Sensors drift, and messages arrive late. None of this is in the Python model, so a trajectory that is perfect on the screen can miss by centimeters on the machine.
A common false comfort is the round trip: give a target to IK, give the angles to FK, and get the target back to six decimal places. This shows only that the two functions agree with each other. If both use m and the real link is 0.79 m, the round trip is still perfect and the real gripper is 10 mm away. Check the model against something outside it, in two steps:
A case solved by hand. Use a pose where the answer is plain from the geometry, such as the two FK poses above, or a move whose end is known. This finds errors in the code: a wrong sign, degrees mixed with radians, the two links exchanged.
One measurement on the machine. Command one pose and measure where the gripper is with a ruler, or time one move with a stopwatch. This finds errors in the numbers. For the pick position , a shoulder whose zero is off by moves the gripper by mm, where 1.44 m is the distance from the base.
Then close the gap where it matters:
Log the error. Run the planned trajectory on the real arm and record the joint position error at every control cycle. The record shows which effect is largest.
Add simple models of the largest effects (the speed limit of the motor, backlash, delay) to the simulator, with the values you measured.
Use feedback on the robot. Follow the trajectory with position feedback, and do not play it back blind.
Keep a margin. Do not design a process that needs 0.1 mm if the measured error is 0.5 mm.
ROS, MoveIt, and the URDF Ecosystem
Work on real robots mostly uses ROS (Robot Operating System), a set of open software for robots. Its main parts:
URDF (Unified Robot Description Format) is the standard file that describes a robot: links, joints, joint limits, shapes and masses. Many manufacturers publish one for their arms. Load it with urdfpy, pinocchio or robotics_toolbox. It holds everything the DH parameters hold, and more.
MoveIt is a motion-planning framework that works from a URDF. It combines IK solvers (KDL, TRAC-IK, BioIK), path planners (OMPL), collision checking (FCL) and monitoring of the motion.
Gazebo, Drake and PyBullet are simulators with physics: forces, masses, contact and sensor models. The simulator of this lesson has positions only. Use a physics simulator to test a controller before it runs on a real arm.
ROS topics and actions carry JointTrajectory messages from the planner to the robot. A trajectory calculated in NumPy converts to a trajectory_msgs/JointTrajectory in about ten lines of code.
The Python simulator of this lesson is the right place to learn the algorithms. Move to ROS and MoveIt when you have a real arm, or more than one person on the project.
Always Export Trajectories
Save every trajectory to a file (CSV or NumPy .npz) with the times, the joint angles, the joint velocities and the commanded position of the gripper. A saved trajectory can be replayed, compared with another plan, plotted, or given to a controller for a test on hardware, and none of these needs the planner to run again.
Course Summary
The six lessons of the Robotics course, and what each one added:
Robot Arm Geometry and Configuration
Established the foundation: link lengths, joint types (revolute, prismatic), workspace geometry, and common architectures (SCARA, articulated, delta). These parameters define what a robot can physically reach.
Forward and Inverse Kinematics
Derived the FK equations that map joint angles to end-effector positions, and the IK equations that solve the reverse problem. Handled multiple solutions and workspace boundaries, the core position-level tools used throughout the course.
Orientation and Quaternions
Introduced Euler angles, exposed their gimbal lock limitation, and developed quaternion mathematics for singularity-free orientation representation. SLERP interpolation provided smooth rotational motion, essential for 6-DOF robots.
Velocity Kinematics and the Jacobian
Built the Jacobian matrix linking joint velocities to task-space velocities. Analyzed singularities, computed manipulability ellipsoids, and introduced damped least-squares for stable velocity control near singular configurations.
Trajectory Planning and Motion Control
Compared joint-space and task-space planning. Implemented cubic and quintic polynomial interpolation, trapezoidal velocity profiles, and multi-point path sequencing for complete pick-and-place operations.
Robot Simulation and Practical Applications (this lesson)
Combined all previous concepts into a complete Python simulation framework with real-time visualization, safety systems, multi-robot coordination, and application across manufacturing, logistics, medical, and agricultural domains.
What You Can Build Now
With the tools from this course, you can:
Design robot arm configurations for specific workspace requirements
Solve forward and inverse kinematics for planar and spatial arms
Plan smooth, safe trajectories with velocity and acceleration limits
Detect and avoid singularities using Jacobian analysis
Build Python simulations to prototype and validate robotic systems
Coordinate multiple robots in shared workspaces
Where to Go Next
This course covered kinematics (position, velocity, trajectory). The natural next steps are:
Dynamics: forces, torques, and the equations of motion (Lagrangian and Newton-Euler methods)
Control: PID, computed torque, and impedance control for real hardware
Perception: computer vision and sensor fusion for autonomous operation
Planning under uncertainty: probabilistic roadmaps, RRT, and motion planning in cluttered environments
Comments
Loading comments...
Predict first
You write a simulator for a two-link arm. To test it, you give a target point to the inverse kinematics, give the joint angles it returns to the forward kinematics, and get the target point back, correct to six decimal places. What has the test shown?
See it: the same move in the simulator and with a real motor
Peak speed the plan asks for
Largest lag behind the plan
Arrival (plan / real joint)
The move is the largest one in the harvesting cell: the shoulder of the left arm turns 266.3° to carry a fruit to its bin. The simulator has no motor, so it follows the dashed plan at any speed. The solid line is a joint with one fault only, a top speed. A real motor also needs time to change speed, so a real joint is later still.
Check yourself
Three questions. Each wrong choice is a mistake people really make, so read the note after you answer.
1. You want to check a forward kinematics function by hand. The arm has L1 = 1.0 m and L2 = 0.8 m. You choose θ1 = 90° and θ2 = −90°. Where must the gripper be?
2. A simulator moves a joint 120° in 0.8 s with a cubic trajectory, and the animation runs with no warning. The motor of the real joint has a top speed of 180 deg/s. Can the real joint follow the plan?
3. Your simulator gives the right answer for two poses you solved by hand. On the real arm, at one commanded pose, a ruler shows the gripper 18 mm from where the simulator says it is. What should you do first?
Watch it build: four tests at every time step
At every time step the simulator checks four things before it accepts the new pose.
Joint 2 stops at ±174.3°. The last 11.5° before link 2 folds onto link 1 are not allowed.
Here det J = 0.8 sin 40° = 0.51. The straight arm has det J = 0; below 0.05, damping starts.
A target 2.30 m away is outside the 1.8 m reach. It moves in to 1.75 m.
A second arm 2.0 m away: its link 2 crosses link 2 of the first. A collision.
Found this useful?
Discussion
No comments yet. Questions, results from your own build, a better way to explain it: all welcome.
Text size
←→
Previous and next card. On a turned card: Not yet, I knew it
SpaceEnter
Turn the card, show the answer
123
Overview, Recap, Test me
HomeEnd
First and last card
Esc
Close
← → or scroll · N notes · F full screen · B blank0:00
My notes on this page
Kept on this device only. Nothing is sent anywhere.
Tip: select words in the lesson, or tap a figure or an equation, to put a note right there.
Notes on earlier wording
The lesson has changed and these words are no longer in it. Your notes are kept, with the words you chose.
Comments