Week 2- 2R Robotic Arm Challenge
AIM:To write a program in MATLAB to simulate the forward kinematics of a 2R Robotic Arm.
CODE:
%2R Robotic Arm Challenge
clear all
close all
clc
%Inputs
l1=2;
l2=1;
theta1=linspace(0, 90, 20);
theta2=linspace(0, 90, 20);
ct=1;
for i=1:length(theta1)
Theta1=theta1(i);
for j=1:length(theta2)
Theta2=theta2(j);
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',3)
axis([-1 5 -1 5]);
pause(0.00001)
M(ct) = getframe(gcf);
ct = ct+1;
end
end
%creation of AVI file
movie(M)
videofile = VideoWriter('forward_kinematics.avi', 'Uncompressed AVI');
open(videofile)
writeVideo(videofile, M)
close(videofile)
EXPLANATION:
- l1 & l2 are lengths of input links (lines 7 and 8).
- theta1 is the angle between ground and link1; theta2 is the angle between ground and link2. Both are row vector (lines 10 and 11).
- ‘ct’ is a counter variable (explained later).
- From line 15 onwards, we have two for loops. Purpose of two for loops is to loop all values of theta2 for each theta1 using variables ‘Theta1’ and ‘Theta2’.
- Inside for loop, we’ll be plotting two lines, let line1 have end points (x0, y0) and (x1, y1); and line2 have (x1, y1) and (x2, y2). What’s happening inside for loop is that we are plotting all possible line2 (for given theta2) for each line1.
- To get all the plots one by one in the same figure window, we’ll be using plot command instead of line command, and store each frame in matrix ‘M’. Here is where we make use of ‘ct’ variable.
- In order to get an animation video, the most efficient way is to create a movie, using movie command. (line 41)
- In line 42, a video file is created using VideoWriter command, with is name and type specified in parenthesis.
- In line 43, first we open the videofile, using ‘writeVideo’ command, we save the frames from matrix ‘M’ in videofile in line 44, and then in line 45, we close the video file.
LINK:
https://drive.google.com/file/d/1WXV1Evkhhd_gq9_PgNiXrHjtqFdFp_5_/view?usp=sharing