Class: Denko::Motor::Servo

Inherits:
Object
  • Object
show all
Includes:
Behaviors::Lifecycle, Behaviors::SinglePin
Defined in:
lib/denko/motor/servo.rb

Constant Summary collapse

FREQUENCY =
50
PERIOD_NS =
20_000_000

Constants included from Behaviors::Lifecycle

Behaviors::Lifecycle::CALLBACK_METHODS

Instance Attribute Summary collapse

Attributes included from Behaviors::SinglePin

#mode, #pin

Attributes included from Behaviors::Component

#board, #params

Attributes included from Behaviors::State

#state

Instance Method Summary collapse

Methods included from Behaviors::Lifecycle

included

Methods included from Behaviors::SinglePin

#convert_pins, #initialize_pins

Methods included from Behaviors::Component

#initialize, #micro_delay

Methods included from Behaviors::State

#update_state

Instance Attribute Details

#maxObject



22
23
24
# File 'lib/denko/motor/servo.rb', line 22

def max
  @max ||= params[:max] || 2500
end

#minObject



18
19
20
# File 'lib/denko/motor/servo.rb', line 18

def min
  @min ||= params[:min] || 500
end

Instance Method Details

#attachObject



28
29
30
31
32
33
34
# File 'lib/denko/motor/servo.rb', line 28

def attach
  if board.platform == :arduino
    board.servo_toggle(pin, :on, min: min, max: max)
  else
    board.set_pin_mode(pin, :output_pwm, {frequency: FREQUENCY, period: PERIOD_NS})
  end
end

#detachObject



36
37
38
# File 'lib/denko/motor/servo.rb', line 36

def detach
  board.servo_toggle(pin, :off) if board.platform == :arduino
end

#position=(value) ⇒ Object Also known as: angle=



40
41
42
43
44
45
46
47
# File 'lib/denko/motor/servo.rb', line 40

def position=(value)
  value = value % 180 unless value == 180

  microseconds = ((value.to_f / 180) * (max - min)) + min
  write_microseconds(microseconds)

  self.state = value
end

#speed=(value) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/denko/motor/servo.rb', line 49

def speed=(value)
  raise 'invalid speed value' if value > 100 || value < -100

  microseconds = (((value.to_f + 100) / 200) * (max - min)) + min
  write_microseconds(microseconds)

  self.state = value
end

#write_microseconds(value) ⇒ Object



63
64
65
66
67
68
69
70
# File 'lib/denko/motor/servo.rb', line 63

def write_microseconds(value)
  raise 'invalid microsecond value' if value > max || value < min
  if board.platform == :arduino
    board.servo_write(pin, value)
  else
    board.pwm_write(pin, (value * 1000.0).round)
  end
end