Skip to content

Commit d57b406

Browse files
Class for controlling and plotting n-link arm
1 parent ce36e2c commit d57b406

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

RoboticArm/NLinkArm.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""
2+
Class for controlling and plotting an arm with an arbitrary number of links.
3+
4+
Author: Daniel Ingram
5+
"""
6+
7+
import numpy as np
8+
import matplotlib.pyplot as plt
9+
10+
class NLinkArm(object):
11+
def __init__(self, link_lengths, joint_angles, goal):
12+
self.n_links = len(link_lengths)
13+
if self.n_links is not len(joint_angles):
14+
raise ValueError()
15+
16+
self.link_lengths = np.array(link_lengths)
17+
self.joint_angles = np.array(joint_angles)
18+
self.points = [[0, 0] for _ in range(self.n_links+1)]
19+
20+
self.lim = sum(link_lengths)
21+
self.goal = np.array(goal).T
22+
23+
self.fig = plt.figure()
24+
self.fig.canvas.mpl_connect('button_press_event', self.click)
25+
26+
plt.ion()
27+
plt.show()
28+
29+
self.update_points()
30+
31+
def update_joints(self, joint_angles):
32+
self.joint_angles = joint_angles
33+
self.update_points()
34+
35+
def update_points(self):
36+
for i in range(1, self.n_links+1):
37+
self.points[i][0] = self.points[i-1][0] + self.link_lengths[i-1]*np.cos(np.sum(self.joint_angles[:i]))
38+
self.points[i][1] = self.points[i-1][1] + self.link_lengths[i-1]*np.sin(np.sum(self.joint_angles[:i]))
39+
40+
self.end_effector = np.array(self.points[self.n_links]).T
41+
self.plot()
42+
43+
def plot(self):
44+
plt.cla()
45+
46+
for i in range(self.n_links+1):
47+
if i is not self.n_links:
48+
plt.plot([self.points[i][0], self.points[i+1][0]], [self.points[i][1], self.points[i+1][1]], 'r-')
49+
plt.plot(self.points[i][0], self.points[i][1], 'ko')
50+
51+
plt.plot(self.goal[0], self.goal[1], 'gx')
52+
53+
plt.plot([self.end_effector[0], self.goal[0]], [self.end_effector[1], self.goal[1]], 'g--')
54+
55+
plt.xlim([-self.lim, self.lim])
56+
plt.ylim([-self.lim, self.lim])
57+
plt.draw()
58+
plt.pause(0.0001)
59+
60+
def click(self, event):
61+
self.goal = np.array([event.xdata, event.ydata]).T
62+
self.plot()

0 commit comments

Comments
 (0)