a = 40; %motor's connection radius
c = 60; %gear radius
P1 = [0 0]; %motor's connection center
P4 = [210 0]; %gear's center
axis(gca,'equal');
axis([-60 300 -60 60]);
k = 1;
for t= 1:1000
theta = k*(t/0.5);
b = sqrt( (210 - 40*cosd(theta)).*(210 - 40*cosd(theta)) +
(40*sind(theta)).*(40*sind(theta)) - 3600); %distance between P2 and P3
P2 = a*[cosd(theta) sind(theta)]; % the point of the motor's circular rotation
X = [P2;P4];
h = pdist(X,'euclidean'); % distance between P2 and P4
alfa = asin(a*sind(theta)/h); %angle between P4-P2 and P4-P1
gamma = asin(b/h); %angle between P4-P2 and P4-P3
P3 = [(210 - c*cos(alfa + gamma)) (c*sin(alfa + gamma))]; % the tangent point
where rod touches the gear
crank = line([P1(1) P2(1)],[P1(2) P2(2)]);
crank2 = line([P4(1) P3(1)],[P4(2) P3(2)]);
rod = line([P3(1) P2(1)],[P3(2) P2(2)]);
P2_traj = viscircles([0 0],a,'LineStyle','--');
P3_traj = viscircles([210 0],c,'LineStyle','--');
P1_circ = viscircles(P1,1);
P2_circ = viscircles(P2,1);
P3_circ = viscircles(P3,1);
P4_circ = viscircles(P4,1);
pause(0.001);
delete(crank);
delete(P1_circ);
delete(P2_circ);
delete(rod);
delete(P3_circ);
delete(P4_circ);
end