lib/artoo/drivers/button.rb in artoo-arduino-1.0.5.pre vs lib/artoo/drivers/button.rb in artoo-arduino-1.1.0

- old
+ new

@@ -1,59 +1,42 @@ require 'artoo/drivers/driver' module Artoo module Drivers - # Button driver behaviors for Firmata + # Button driver behaviors class Button < Driver COMMANDS = [:is_pressed?].freeze DOWN = 1 UP = 0 # @return [Boolean] True if pressed def is_pressed? - (@is_pressed ||= false) == true + (@pressed_val == 1) ? true : false end - # Sets values to read and write from button - # and starts driver def start_driver - connection.set_pin_mode(pin, Firmata::PinModes::INPUT) - connection.toggle_pin_reporting(pin) + @pressed_val = 0 every(interval) do - connection.read_and_process - handle_events + new_value = connection.digital_read(pin) + update(new_value) if !new_value.nil? && new_value != is_pressed? end super end - def handle_events - while i = find_event("digital_read_#{pin}") do - event = events.slice!(i) - update(event.data.first) if !event.nil? - end - end - - def find_event(name) - events.index {|e| e.name == name.to_sym} - end - - def events - connection.async_events - end - + private # Publishes events according to the button feedback - def update(value) - if value == DOWN - @is_pressed = true - publish(event_topic_name("update"), "push", value) - publish(event_topic_name("push"), value) + def update(new_val) + if new_val == 1 + @pressed_val = 1 + publish(event_topic_name("update"), "push", new_val) + publish(event_topic_name("push"), new_val) else - @is_pressed = false - publish(event_topic_name("update"), "release", value) - publish(event_topic_name("release"), value) + @pressed_val = 0 + publish(event_topic_name("update"), "release", new_val) + publish(event_topic_name("release"), new_val) end end end end end