-
Notifications
You must be signed in to change notification settings - Fork 4
/
motordriver.rb
54 lines (44 loc) · 1006 Bytes
/
motordriver.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
require './arduino.rb'
class MotorDriver
def initialize(arduino, motors={})
@arduino = arduino
@motors = motors
end
def close
@arduino.close
end
def all(*args)
@motors.values.each{ |e| e.send(args[0].to_sym, *args[1..-1])}
end
def method_missing(m, *args)
if @motors[m]
puts "Motor #{m} #{args}"
@motors[m].send(args.shift.to_sym, *args)
else
super
end
end
end
class Motor
FORWARD = 1
BACKWARD = 2
BREAK = 3 #do not use
RELEASE = 4
def initialize(nr, arduino, commands={})
@nr = constrain(nr, 1, 4)
@arduino = arduino
@commands = {:forward=>FORWARD, :backward=>BACKWARD, :stop=>RELEASE}.merge(commands)
end
def method_missing(m, *args)
if @commands[m]
@arduino.write(@nr, @commands[m], constrain(args.first.to_i || 255, 0, 255))
else
@arduino.write(@nr, @commands[:stop], 0)
super
end
end
private
def constrain(val, min, max)
[min, [max, val].min].max
end
end