USBシリアルケーブルHL-340(pl-2303もテスト済み)を使用して、ラズベリーパイをシリアルポートデバイスに接続しています
デバイスは1 バイトのコマンドを受け取り、 2 バイトで応答する必要があります(OK、これは非常に単純なデバイスであり、非常に習得しやすいプロトコルです :) )
私のコード:
[...]
final int[] status = this.serialPort.getLinesStatus ( );
final StringBuilder sb = new StringBuilder ( "Lines Status:" );
final String[] name = new String[] { "CTS", "DSR", "RING", "RLSD" };
for ( int i = 0; i < status.length; i++ )
sb.append ( ( i > 0 ) ? "," : "" ).append ( name [i] ).append ( ':' ).append ( status [i] );
System.out.println ( sb.toString ( ) );
System.out.println ( "flowcontrol:" + this.serialPort.getFlowControlMode ( ) );
this.serialPort.purgePort ( SerialPort.PURGE_RXCLEAR | SerialPort.PURGE_TXCLEAR );
synchronized ( this )
{
System.out.println ( "1) getInputBufferBytesCount():" + this.serialPort.getInputBufferBytesCount ( ) );
this.serialPort.addEventListener ( this );
this.serialPort.setEventsMask ( SerialPort.MASK_RXCHAR );
this.serialPort.writeBytes ( COMMAND );
wait ( 3000 ); // wait 3 seconds for reply
this.serialPort.removeEventListener ( );
System.out.println ( "2) getInputBufferBytesCount():" + this.serialPort.getInputBufferBytesCount ( ) );
final int n = this.serialPort.getInputBufferBytesCount ( );
if ( n > 0 )
{
this.serialPort.readBytes ( n ); // purge garbage data?
System.out.println ( "3) getInputBufferBytesCount():" + this.serialPort.getInputBufferBytesCount ( ) );
}
}
if ( ( this.data == null ) && ( this.error == null ) )
this.error = "no response from device";
[...]
およびコールバック コード:
@Override
public final void serialEvent ( final SerialPortEvent event )
{
synchronized ( this )
{
try
{
final int val;
if ( event.isRXCHAR ( ) )
if ( (val = event.getEventValue ( )) == 2 ) // the reply is 2 bytes
this.data = this.serialPort.readBytes ( 2 );
else
this.error = "unexpected value:" + val;
else
this.error = "unexpected event:" + event;
}
catch ( final Throwable x )
{
this.error = x.toString ( );
}
finally
{
notify ( );
}
}
}
結果は非常に奇妙で予測不可能です:(デバイスからの応答として2バイトしか期待していませんが、シリアルポートは読み取り可能なデータがはるかに多いことを通知します:
Lines Status:CTS:0,DSR:0,RING:0,RLSD:0
flowcontrol:0
1) getInputBufferBytesCount():0
2) getInputBufferBytesCount():544
3) getInputBufferBytesCount():0
java.lang.Throwable: unexpected value:192
また
Lines Status:CTS:0,DSR:0,RING:0,RLSD:0
flowcontrol:0
1) getInputBufferBytesCount():0
2) getInputBufferBytesCount():512
3) getInputBufferBytesCount():0
java.lang.Throwable: unexpected value:192
また
Lines Status:CTS:0,DSR:0,RING:0,RLSD:0
flowcontrol:0
1) getInputBufferBytesCount():0
2) getInputBufferBytesCount():32
3) getInputBufferBytesCount():0
java.lang.Throwable: unexpected value:32
問題とは何ですか?どのポート設定を変更する必要がありますか?