Challenge

Week 3.2 - 2R Robotic Arm Challenge

CODE:

clc;

clear;

close all;

%% Define link lengths of the 2R robotic arm
L1 = 10; % Length of first link
L2 = 7; % Length of second link
%% Define joint angles for animation
% theta1 and theta2 represent the angles of the first and second joints respectively
numFrames = 120; % Number of frames in animation
% Generate angles smoothly from 0 to 90 degrees
theta1 = linspace(0, pi/2, numFrames); % Joint 1 angle in radians
theta2 = linspace(0, pi/2, numFrames); % Joint 2 angle in radians
%% Initialize figure for animation
figure;
axis equal;

%%If you don't set limits (xlim and ylim), MATLAB will automatically adjust the axis limits based on the data plotted
%This can Cause, Unstable or Shifting Viewport, Arm going out of view, Inconsistent Scaling.
% In my case, when, I forgot to set limits, MATLAB resized the plot dynamically, Making it Zoom in/ out.
xlim([-L1-L2, L1+L2]);
ylim([-L1-L2, L1+L2]);
xlabel('X Position');
ylabel('Y Position');
title('2R Robotic Arm Forward Kinematics Animation');
grid on;
hold on;
% Create video writer object to save animation
v = VideoWriter('2R_Robotic_Arm.mp4', 'MPEG-4');
v.FrameRate = 120;
open(v);
%% Animation loop
for i = 1:numFrames
% Calculate Joint Positions using Forward Kinematics
x0 = 0; y0 = 0; % Base of robot
x1 = L1 * cos(theta1(i));
y1 = L1 * sin(theta1(i));
x2 = x1 + L2 * cos(theta1(i) + theta2(i));
y2 = y1 + L2 * sin(theta1(i) + theta2(i));
% Plot the arm
cla; % Clear previous frame
plot([x0, x1], [y0, y1], 'r-', 'LineWidth', 3); % First link
hold on;
plot([x1, x2], [y1, y2], 'b-', 'LineWidth', 3); % Second link
plot(x0, y0, 'ko', 'MarkerSize', 8, 'MarkerFaceColor', 'k'); % Base
plot(x1, y1, 'go', 'MarkerSize', 8, 'MarkerFaceColor', 'g'); % Joint 1
plot(x2, y2, 'bo', 'MarkerSize', 8, 'MarkerFaceColor', 'b'); % End Effector
% Update figure and capture frame
drawnow;
frame = getframe(gcf);
writeVideo(v, frame);
end
% Close video writer
close(v);

%% Errors: Forgot to set the limits ( explained at the code part _ Xlim & Ylim . Also attached a mp4 file.

% output

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.