2R Robotic Arm Simulator on Python
This code simulates a 2 link robot with each link travelling from 0 degree to 90 degrees.
# 2R Robotic Arm Simulator
import matplotlib.pyplot as plt
import numpy as np
import math
import os
# Inputs
start_angle = 0
end_angle = math.pi/2
x0 = 0 # x-co-ordinate of Link 1, base connector
y0 = 0 # y-co-ordinate of Link 1, base connector
l1 = 1 # Length of link 1
l2 = 0.5 # Length of link 2
angular_divisions = 9
theta = np.arange(start_angle,end_angle+(end_angle-start_angle)/angular_divisions,(end_angle-start_angle)/angular_divisions)
# Initilize
x1=[]
y1=[]
x2=[]
y2=[]
i=0
# Calulation
for t1 in theta:
x1.append((l1*math.cos(t1)))
y1.append((l1*math.sin(t1)))
j=0
for t2 in theta:
x2.append((x1[i]+l2*math.cos(t2)))
y2.append((y1[i]+l2*math.sin(t2)))
plt.figure()
plt.plot([x0,x1[i]],[y0,y1[i]])
plt.plot([x1[i],x2[j+(angular_divisions+1)*i]],[y1[i],y2[j+(angular_divisions+1)*i]])
plt.xlim(-0.5,2)
plt.ylim(-0.5,2)
filenumber=j+(angular_divisions+1)*i
filenumber=format(filenumber,"05")
filename="image{}.png".format(filenumber)
plt.savefig(filename)
plt.close()
j=j+1
i=i+1
os.system("ffmpeg -f image2 -r 20 -i image%05d.png -vcodec mpeg4 -y movie.avi")
Note:-
The code generates multiple images corresponding to each angular step taken by the links.The images are saved in the same directory in which the code is saved. To generate a video from the images ffmpeg library is used. This is not a python library. Python sends string of arguments (which is defined in ffmpeg library) to Operating system as shown in the last code line of the program. Operating system looks for the definition of this comapnd from the ffmpeg library and thus, stiches the images to form movie.avi'. If movie is not required to be generated, comment out the last line of the code by using #.
Link to download ffmpeg:-
https://ffmpeg.zeranoe.com/builds/
https://youtu.be/rAJW_7Or9us