Simulation of the Forward Kinematics of a 2R Robotic Arm
Objective: To write a program in python to simulate the forward kinematics of a 2R robotic arm, i.e., to create an animation showing the positions of the manipulator and links for different values of link angles.
Procedure:-
- We write a python programme which calculates the position of the manipulator for different values of the link angles. The plots are generated for each case, showing the positions of the manipulator as well as the links. Each of the plots is saved as a separate PNG file. The code along with the explanation of different steps (mentioned as comments in the code) is described below:-
"""
Simulation of the forward kinematics of a 2R robotic arm:-
-> plotting the manipulators position for different values of link 1 and link 2 angles with the x-axis
-> saving all the plots maintaining the proper sequence of the filenames so that we are ready to stitch a GIF out of it.
"""
import math
import matplotlib.pyplot as plt
# Inputs: Lets take the lengths of our two links to be 2 and 1.5 units respectively
l1 = 2
l2 = 1.5
# Calculating the manipulator's postion for different angles which the two links make with the x-axis
# Lets calculate for 20 angles in between 0 and 180 degrees (pi radians)
n_theta = 15
theta_start = 0
theta_end = (math.pi)
theta1 = []
theta2 = []
for i in range(0,n_theta):
theta = theta_start + i*(theta_end - theta_start)/(n_theta - 1)
theta1.append(theta)
theta2.append(theta)
# Base of the robot: Lets take it to be the origin, i.e., at a coordinate of (0,0)
x0 = 0
y0 = 0
# Defining a variable ct to be able to save each of the plots to a separate file
ct = 1
for t1 in theta1:
for t2 in theta2:
# Link 1, link 2 connector
x1 = x0 + l1*math.cos(t1)
y1 = y0 + l1*math.sin(t1)
#Coordinates of the manipulator
x2 = x1 + l2*math.cos(t2)
y2 = y1 + l2*math.sin(t2)
# The following syntax ensures that we are able to maintain proper sequence while saving the different plots
filename = 'test%05d.png' %ct
ct = ct + 1
plt.figure()
plt.plot([x0,x1],[y0,y1])
plt.plot([x1,x2],[y1,y2])
plt.xlim([-4,4])
plt.ylim([-4,4])
plt.savefig(filename)
- After obtaining all the plots, a GIF is created by stitching them together. This is done using ImageMagick software. All the PNG files are moved to a folder and by executing the command, the GIF is created.
Result:-
We get the animation which shows the positions of the manipulator as well as the links for different values of the link angles.
The link to the animation video is: