Skip to content

Instantly share code, notes, and snippets.

@dcrosby42
Created December 4, 2012 05:40
Show Gist options
  • Save dcrosby42/4201028 to your computer and use it in GitHub Desktop.
Save dcrosby42/4201028 to your computer and use it in GitHub Desktop.
JrSerialPort Example Code
require 'java'
require_relative 'RXTXcomm.jar'
import('gnu.io.CommPortIdentifier')
import('gnu.io.SerialPort') { 'GnuSerialPort' }
class JrSerialPort
NONE = GnuSerialPort::PARITY_NONE
def initialize name, baud, data, stop, parity
port_id = CommPortIdentifier.get_port_identifier name
data = GnuSerialPort.const_get "DATABITS_#{data}"
stop = GnuSerialPort.const_get "STOPBITS_#{stop}"
@port = port_id.open 'JRuby', 500
@port.set_serial_port_params baud, data, stop, parity
@in = @port.input_stream
@in_io = @in.to_io
@out = @port.output_stream
end
def close
@port.close
end
def write(s)
@out.write s.to_java_bytes
end
def read
@in_io.read(@in.available) || ''
end
end
require_relative 'jr_serial_port'
port_name = ARGV.shift || '/dev/ttyUSB0'
serial_port = JrSerialPort.new port_name, 19200, 8, 1, JrSerialPort::NONE
Thread.new do
while true do
sleep 0.01
print serial_port.read
end
end
while true
print "Prompt> "
serial_port.write gets.strip
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment