JP *_*shy 5 ruby serial-port arduino
我不清楚如何使用ruby编写简单的字节代码数组,所以我完全不知道如何使用Ruby SerialPort库,说实话我已经很好地工作但是我只是成功了通过串口发送ASCII.
例如,编写ASCII非常简单:
@sp = SerialPort.new "/dev/tty.usbserial-A6004cNN", 19200
@sp.write "test"
Run Code Online (Sandbox Code Playgroud)
显然写入test该串行设备.这很好用,在这种情况下,我已经能够将所有预期结果发送到微控制器(arduino).问题是我需要编写串行设备将读取的输出,如下所示:
{0x01,0x09,0x04,0x00, 'f',0xff,0xcc,0x33}
Run Code Online (Sandbox Code Playgroud)
我已尝试使用str.unpack但仍无法按上述字节生成所需的十六进制值输出.
在Java中,使用它的串行库很简单:
byte[] cmd = { 0x01,0x09,0x04,0x00, 'f',(byte)0xff,(byte)0xcc,(byte)0x33 };
serialPort.write( cmd );
Run Code Online (Sandbox Code Playgroud)
如何使用Ruby将正确的字节码输出到我的串行设备?
@sp.write [32.chr, 7.chr, 8.chr, 65.chr].to_s
@sp.write ["\x01\x09\x04\x00", 'f', "\xff\xcc\x33"].to_s
Run Code Online (Sandbox Code Playgroud)
但我们可以有更多的乐趣(muhahaha ...)
class Array
def chr
self.map { |e| e.chr }
end
end
Run Code Online (Sandbox Code Playgroud)
那么:
>> [1,2,3,65,66,67].chr
=> ["\001", "\002", "\003", "A", "B", "C"]
>> [1,2,3,65,66,67].chr.to_s
=> "\001\002\003ABC"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2688 次 |
| 最近记录: |