Program in Matlab to Simulate the Forward Kinematics of a 2R Robotic Arm
The MATLAB code is to simulate the forward kinematics of a 2R Robotic Arm.
Firstly in line 8 & 9, arm length variables are declared and initialized.
Line 12 & 13, Arm angle variables are initialised by using linspace function i.e. 'theta1' from 0 to 180 with 30 intervals and 'theta2' from 15 to 165 with 30 intervals.
Variable 'theta2' starts from 15 and ends to 165 just to avoid interference from arm 1. Variable 'ctr' is the loop control variable.
From line 17 to 32, Nested loop statement is used to calculate the initial and final coordinates of both the arms.
Line 35, is the combined plot statement for both the arms.
In line 45, all the plot figure window are captured through getframe function and stored in an array 'M'.
In line 46, a movie is created by using movie function from array 'M'.
From line 47 to 50, a video file is created named 'forward_kinematics.avi' and the movie of 'M' array is stored in it.
------------------------------------------------------------------------------------------------------------
The output as a video can be viewed at the below link:
------------------------------------------------------------------------------------------------------------
Errors Faced While Programming
- Plot Command plot([x0 y0], [x1 y1], [x2 y2])
Solution plot([x0 x1], [y0 y1], [x1 x2], [y1 y2])
- Line 41 typo error in write video command WriteVideo(videofile, M)
Solution writeVideo(videofile, M)
% Forward Kinematics of a 2R Robotic Arm
clear all
close all
clc
%Arm Length Variables
l1=1;
l2=0.5;
%Arm Angle Variables
theta1=linspace(0,180,30);
theta2=linspace(15,165,30);
ctr=1;
%Loop Statement
for i = 1:length(theta1)
THETA1 = theta1(i);
for j = 1:length(theta2)
THETA2 = theta2(j);
%Initial Coordinates of 1st arm
x0 = 0;
y0 = 0;
%Final Coordinates of 1st Arm and Initial Coordinates of 2nd Arm
x1 = l1*cosd(THETA1);
y1 = l1*sind(THETA1);
%Final Coordinates of 2nd Arm
x2 = x1 + l2*cosd(THETA2);
y2 = y1 + l2*sind(THETA2);
%Combined Plot Statement of both the arms
plot([x0 x1],[y0 y1],[x1 x2],[y1 y2],'linewidth',3)
axis([-1.8 1.8 -1.8 1.8])
pause(0.1)
%Array M stores all the figure window
M(ctr) = getframe(gcf);
ctr = ctr+1;
end
end
movie(M);
videofile = VideoWriter('forward_kinematics.avi', 'uncompressed AVI')
open(videofile)
writeVideo(videofile,M)
close(videofile)