Class: Frankenpins::RotaryEncoder

Inherits:
Object
  • Object
show all
Includes:
Unobservable::Support
Defined in:
lib/frankenpins/rotary_encoder.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ RotaryEncoder

Returns a new instance of RotaryEncoder.



9
10
11
12
13
14
15
16
17
# File 'lib/frankenpins/rotary_encoder.rb', line 9

def initialize(options)
  @pin_a, @pin_b = create_pins_from_options_hash!(options)

  @pin_a.watch { update }
  @pin_b.watch { update }

  @position = 0
  @last_val = 0
end

Instance Method Details

#updateObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/frankenpins/rotary_encoder.rb', line 19

def update
  @pin_a.read
  msb = @pin_a.value

  @pin_b.read
  lsb = @pin_b.value

  encoded = (msb << 1) | lsb;
  sum = (@last_val << 2) | encoded;

  if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011)
    @position += 1
    raise_event :changed, @position, :clockwise
  end
  if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000)
    @position -= 1
    raise_event :changed, @position, :anticlockwise
  end

  @last_val = encoded
end

#when(event_name, &block) ⇒ Object



41
42
43
# File 'lib/frankenpins/rotary_encoder.rb', line 41

def when(event_name, &block)
  send(event_name).register(&block)
end