Created
December 4, 2012 05:40
-
-
Save dcrosby42/4201028 to your computer and use it in GitHub Desktop.
JrSerialPort Example Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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