Program to simulate the forward kinematics of a 2R Robotic Arm
Objective:
- To write a program to simulate the forward kinematics of a 2R Robotic Arm
- To create an animation file of the plot
Program:
'''Program for 2R Robotic arm simulator.
there are two links of length, l1 and l2 respectively.
theta_1 and theta_2 are the angles made by these links with the horizontal at different instances.
the base point of link_1 is [x0, y0], link_2 is [x1, y1] and the position of the manipulator is [x2, y2]
x1 = l1 * cos(theta_1)
y1 = l1 * sin(theta_1)
similarly,
x2 = x1 + l2 * cos(theta_2)
y2 = y1 + l2 * sin(theta_2)
we need to create a program to animate the positions of the two arms when theta_1 and theta_2 value lies between 0 to 90 degree.
'''
import math
import matplotlib.pyplot as plt
import numpy as np
l1 = 1
l2 = 1
x0 = 0
y0 = 0
theta_start = 0
theta_end = math.pi/2
n_theta = 10
theta_1 = []
theta_2 = []
for i in range(0,n_theta):
theta_tmp = theta_start + (i * (theta_end - theta_start)/(n_theta - 1))
theta_1.append(theta_tmp)
theta_2 = theta_1
print(theta_1)
print(theta_2)
count = 1
for t1 in theta_1:
for t2 in theta_2:
x1 = l1 * math.cos(t1)
y1 = l1 * math.sin(t1)
x2 = x1 + l2 * math.cos(t2)
y2 = y1 + l2 * math.sin(t2)
filename = '%05d.png' % count # %05d is used so that the images are arranged in the same order when called in cmd
count = count +1
plt.figure()
plt.plot([x0,x1],[y0,y1])
plt.plot([x1,x2],[y1,y2])
plt.xlim([-1,3])
plt.ylim([-1,3])
plt.savefig(filename)
#for converting to gif, go to the folder in which the images are saved using cmd and then use 'magick *.png name.gif' command to combine all the images in the folder and create a gif.
Explanation:
- Imported the necessary modules
- Defined the variables.
- Used a for loop for creating the list of theta values ranging from 0 to 90 degrees (theta_1 and theta_2 both)
- Used a for loop to get the values of (x1,y1) and (x2,y2) for every theta_1 and theta_2 in the range(0 to 90 degrees)
- Used the values of x1, x2, and y1, y2 to plot the robotic arm position at different instances.
- Saved all the plots in a folder and combined them together in the correct sequence using ImageMagick for creating a gif file showing the motion of the two links of the robotic arm.
Output:
- The output is the animation of the motion of the robotic arm for theta varying from 0 to 90 degrees.