class Duino
Public Class Methods
new(port, baudrate=115200)
click to toggle source
# File lib/duino.rb, line 4 def initialize(port, baudrate=115200) data_bits = 8 stop_bits = 1 parity = SerialPort::NONE @serial = SerialPort.new(port, baudrate, data_bits, stop_bits, parity) @serial.read_timeout = 2 @serial.sync @port = port @output_pins = [] @input_pins = [] @pin_states = {} puts "Initialized" end
Public Instance Methods
analog_read(pin)
click to toggle source
# File lib/duino.rb, line 88 def analog_read(pin) send_data(4) send_pin(pin) get_data() end
analog_write(pin, value)
click to toggle source
# File lib/duino.rb, line 81 def analog_write(pin, value) send_data(3) send_pin(pin) send_data((value / 16).to_s(16)) send_data((value % 16).to_s(16)) end
close()
click to toggle source
# File lib/duino.rb, line 101 def close send_data(5) @serial.dtr = (0) @serial.close puts "Connection closed" end
digital_input(*pin_list)
click to toggle source
# File lib/duino.rb, line 37 def digital_input(*pin_list) send_data(pin_list.length) if(pin_list.class == Array) @input_pins = pin_list pin_list.each do |pin| send_pin(pin) end else raise ArgumentError, "Arguments must be a list of pin numbers" end return pin_list end
digital_output(*pin_list)
click to toggle source
# File lib/duino.rb, line 24 def digital_output(*pin_list) send_data(pin_list.length) if(pin_list.class == Array) @output_pins = pin_list pin_list.each do |pin| send_pin(pin) end else raise ArgumentError, "Arguments must be a list of pin numbers" end return pin_list end
get_state(pin)
click to toggle source
# File lib/duino.rb, line 66 def get_state(pin) # Returns true if high and false if low. send_data(2) send_pin(pin) while true rval = @serial.getbyte() if(rval == 0) return("Low") end if(rval == 1) return("High") end end end
save_state(pin, state)
click to toggle source
# File lib/duino.rb, line 62 def save_state(pin, state) @pin_states[pin.to_s] = state end
set_high(pin)
click to toggle source
# File lib/duino.rb, line 50 def set_high(pin) save_state(pin, true) send_data(1) send_pin(pin) end
set_low(pin)
click to toggle source
# File lib/duino.rb, line 56 def set_low(pin) save_state(pin, false) send_data(0) send_pin(pin) end
to_s()
click to toggle source
# File lib/duino.rb, line 20 def to_s "Arduino is on port #{@port} at #{@serial.baud} baudrate" end
turn_off()
click to toggle source
# File lib/duino.rb, line 94 def turn_off @output_pins.each do |pin| set_low(pin) end puts "All pins set to low" end
Private Instance Methods
get_data()
click to toggle source
# File lib/duino.rb, line 121 def get_data clean_data = @serial.readlines() clean_data = clean_data.join("").gsub("\n","").gsub("\r","") end
send_data(serial_data)
click to toggle source
# File lib/duino.rb, line 114 def send_data(serial_data) while true break if(get_data() == "?") end @serial.write serial_data.chr end
send_pin(pin)
click to toggle source
# File lib/duino.rb, line 110 def send_pin(pin) send_data(pin) end