Module: Denko::AnalogIO::InputHelper

Included in:
ADS1100, Input, Sensor::VL53L0X
Defined in:
lib/denko/analog_io/input_helper.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#smoothingObject

Smoothing features. Does a moving average of the last smoothing_size readings.



8
9
10
# File 'lib/denko/analog_io/input_helper.rb', line 8

def smoothing
  @smoothing
end

#smoothing_sizeObject

Smoothing features. Does a moving average of the last smoothing_size readings.



8
9
10
# File 'lib/denko/analog_io/input_helper.rb', line 8

def smoothing_size
  @smoothing_size
end

Instance Method Details

#on_change(&block) ⇒ Object

Attach a callback that only fires when state changes.



35
36
37
38
39
# File 'lib/denko/analog_io/input_helper.rb', line 35

def on_change(&block)
  add_callback(:on_change) do |new_state|
    block.call(new_state) if new_state != self.state
  end
end

#pre_callback_filter(value) ⇒ Object

Handle smoothing if enabled. Call super(value) after conversion in subclasses.



30
31
32
# File 'lib/denko/analog_io/input_helper.rb', line 30

def pre_callback_filter(value)
  smoothing ? smooth_input(value.to_i) : value.to_i
end

#smooth_input(value) ⇒ Object



18
19
20
21
22
23
24
25
26
27
# File 'lib/denko/analog_io/input_helper.rb', line 18

def smooth_input(value)
  # Add new value, but limit to the 8 latest values.
  smoothing_set << value
  smoothing_set.shift while (smoothing_set.length > smoothing_size)

  average = smoothing_set.reduce(:+) / smoothing_set.length.to_f

  # Round up or down based on previous state to reduce fluctuations.
  state && (state > average) ? average.ceil : average.floor
end

#smoothing_setObject



14
15
16
# File 'lib/denko/analog_io/input_helper.rb', line 14

def smoothing_set
  @smoothing_set ||= []
end