Ruby - Serialport on Windows
Ruby - Serialport on Windows
ruby-serialport経由でWindowsでもGainer/Ginger/Pepper/Sugarを使えるようにしました。
忘れないうちに、私の実行した手順を記録しておきます。
1.Rubyのインストール
Rubyforgeから1.8.6-27 Release Candidate 2を導入
http://rubyforge.org/frs/?group_id=167&release_id=28426
>ruby -v
ruby 1.8.6 (2008-08-11 patchlevel 287) [i386-mswin32]
2.gemのアップデート
DOS窓を開いて、gemのアップデートを実行
>gem update --system
>gem update
3.Ruby-Serialportのインストール
(1) Rubyforgeのruby-serialportプロジェクトからファイルをダウンロードします。
パッチが出ていますので、パッチ済みのバイナリを入手します.
(2) パッケージの展開
ruby-serialport-0.6.0-mswin32-gem.zipを適当なフォルダに展開します。
(3) gemでローカルインストール
展開してできるgemをローカルにインストールする
>gem install serialport-0.6.0-mswin32.gem
4.Ruby-Serialportのテスト
試しに、Gainer miniを動かしてみます。(test.rb)
require 'rubygems'
require 'serialport'
sp = SerialPort.new("COM3", 9600)
sp.read_timeout=0
sp.write "Q*"
p sp.gets('*');
sp.write "KONFIGURATION_1*"
p sp.gets('*');
sp.write "i*"
while c= sp.gets('*')
puts c
end
結果は次のようになりました。 (Gainer miniはCOM3に割り当てられています。)
>ruby test.rb
"Q*"
"KONFIGURATION_1*"
iFFBAA187*
i73564A42*
i44342C25*
i12080609*
i16120F0B*
i09070504*
i00000000*
i0F100E08*
i00000000*
以下略
5.Gainer-rubyをruby-serialport経由で使えるようにする
Gainer-rubyのパッケージをそのまま配布出来ないので、以下patchをあてて下さい。
*** gainer.rb.orig2009-03-02 06:44:17.000000000 +0900
--- gainer.rb2009-03-05 20:11:54.000000000 +0900
***************
*** 126,162 ****
end
end
! require 'termios'
class Serial < Basic
def initialize(path, config = nil)
! @file = File.open(path, 'w+')
! @file.sync = true
setup_port
-
super(config)
end
private
def setup_port
! setting = Termios::getattr(@file)
! setting.ispeed = setting.ospeed = 38400
! setting.cflag |= Termios::CS8
! Termios::setattr(@file, Termios::TCSANOW, setting)
end
def command_send(c)
! @file.write(c)
end
def next_event
! loop do
! ary = select([@file], [], [], 1)
! if ary and ary[0].include?(@file)
! result = @file.gets('*')
! return result
! end
! end
end
end
--- 126,151 ----
end
end
! require 'serialport'
class Serial < Basic
def initialize(path, config = nil)
! @sp = SerialPort.new(path, 38400)
setup_port
super(config)
end
private
def setup_port
! @sp.read_timeout = 0;
end
def command_send(c)
! @sp.write(c)
end
def next_event
! return @sp.gets('*');
end
end
しばらく、パッケージも置いておきます。gainer-0.0.2.gem
>gem install gainer-0.0.2.gem
テストしてみます。(blink.rb)
require 'rubygems'
require 'gainer'
gainer = Gainer::Serial.new("COM3")
flag = true
while true
gainer.led = flag;
flag = ! flag
sleep(0.2)
end
大丈夫そうです。
ruby-serialportを使うことで,クロスプラットフォームで共通のパッケージが利用出来て便利です。但し、ポート名はOSに依存しますので変更が必要です。
作業に当たりsenshuさんに協力頂きました。感謝します。
2009年3月2日月曜日
Windows上でRubyからGainerを制御する