Week 2- 2R Robotic Arm Challenge
% Forward kinematics of 2R robotic arm
% Inputs
l1 = 5;
l2 = 10;
theta1 = linspace(0,90,5);
theta2 = linspace(0,90,5);
c =1;
for i = 1:length(theta1)
THETA1 = theta1(i);
for j = 1:length(theta2)
THETA2 = theta2(j);
% Coordinates of the starting and end points of the links
x0 = 0;
y0 = 0;
x1 = l1*cosd(THETA1);
y1 = l1*sind(THETA1);
x2 = x1 + l2*cosd(THETA2);
y2 = y1 + l2*sind(THETA2);
% Plotting
plot([x0 x1],[y0 y1],[x1 x2],[y1 y2],'linewidth',2)
grid on
axis([-1 20 0 20])
pause(0.4)
m(c) = getframe(gcf);
c = c+1;
end
end
% Animation
movie(m)
videofile = VideoWriter('forward_kinematics_2r_robotic_arm.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,m)
close(videofile)
Explanation : The above program is used to simulate the forward kinematics of a 2R robotic arm. First, the inputs are defined i.e the length of the two links l1 and l2 as per the program and the angle of the links wirth respect to horizontal ( x axis) i.e theta1 and theta2. c is a constant which is used later in the for loop for animation. Here, theta1 and theta2 are two row vectors created by using linspace command. There are 2 for loops created to get all the possible movements of the robotic arm. In the first for loop, THETA1 is defined such that it covers all the values of theta1 in an order. In the second for loop, THETA2 is defined such that it covers all the values of theta2. Now with these values, the starting point of the first link is taken as orgin ( x0=0 and y0=0), the ending point of the first link or the starting point of the second link are calculated ( x1= l1cosdTHETA1 and y1 = l1sindTHETA1) and the coordinates ending point of the second link are also calculated ( x2 = x1 + l2cosdTHETA2 and y2 = y1 + l2sindTHETA2). Here cosd and sind are used, that indicates that the angles are in degrees. For plotting the graphs that shows the movement of the arm the plot command is used with linewidth 3. The starting and ending of the graph is determined by using axis command. The delay between each graph is 0.4s, for which pause command is used. Next an array "m" is defined such that m(c) = getframe(gcf). The getframe(gcf) captures the entire interior of the current figure window. Before ending the for loops we define c again such that c= c+1 so to get the next frame. The for loops are ended using the end command. The movie command is used to get the animation of the arm by combining all the frames and videofile is defined by using VideoWriter command that specifies the name of the file and the type of file. The open command is used to open the file and play and the close command is used to close the videofile.
The errors I faced while executing the progam are that all the plots get alligned in a single graph and to avoid that the hold on command is removed and insted of using 2 line commands, a single plot command is used.
Google Drive Link : https://drive.google.com/file/d/1un4qu8QW1o0NJzgsDeUFuxVLyM0BhHZD/view?usp=sharing