如何在java中将一个字节序列写入串口

时间:2015-07-06 14:47:00

标签: java serial-port

我是java的初学者。我必须通过com端口向我正在使用的仪器发送5个连续的整数。我正在使用rxtx库。该仪器不响应我的代码。我尝试将值初始化为字符串,然后使用getbytes将其更改为byte。但即使这样也没有帮助。如果有人可以帮助我,那将是一个很大的帮助。该仪器在COM5中确定。我试着先写入Com端口。触发数据可用事件。但输入流读取是无法识别的字符。我认为问题在于写入端口。如果有人可以帮助我,那将是一个很大的帮助。

设备的串行接口规范如下

DIR START CMD VALLO VALHI END

→53 1 4 0 83

←53 1 4 0 83

←53 27 SLO SHI 83

事务由以下数据包序列

定义

•→软件发送请求包。

•←仪器发送响应包。

•←仪器发送状态包。

这表示整个运行中的单个事务。

每个START; CMD; VALLO; VALHI; END表示数据包中的单个字节

public class ReadWrite implements SerialPortEventListener {

    OutputStream outputStream;
    InputStream inputStream;
    static SerialPort serialPort;

    public static void main(String[] args) throws Exception {
        Enumeration portList = CommPortIdentifier.getPortIdentifiers();
        System.out.println("SimpleRead Started.");
        while (portList.hasMoreElements()) {
            CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                System.out.println("Found " + portId.getName());
                if (portId.getName().equals("COM5")) {
                    serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000);
                    serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                    ReadWrite reader = new ReadWrite();
                }
            }
        }
    }

    public ReadWrite() throws IOException {
        try {
            outputStream = serialPort.getOutputStream();
            inputStream = serialPort.getInputStream();

            outputStream.write(53);
            outputStream.flush();
            outputStream.write(1);
            outputStream.flush();
            outputStream.write(4);
            outputStream.flush();
            outputStream.write(0);
            outputStream.flush();
            outputStream.write(83);
            outputStream.flush();

            System.out.println("The port in use is " + serialPort);

            System.out.println("write done");

            serialPort.addEventListener(this);
        } catch (TooManyListenersException e) {
            e.printStackTrace();
        }
        serialPort.notifyOnDataAvailable(true);
    }

    public void serialEvent(SerialPortEvent event) {

        switch (event.getEventType()) {
        case SerialPortEvent.BI:
            System.out.println("The serial port event is BI ");

        case SerialPortEvent.OE:

        case SerialPortEvent.FE:

        case SerialPortEvent.PE:

        case SerialPortEvent.CD:

        case SerialPortEvent.CTS:

        case SerialPortEvent.DSR:

        case SerialPortEvent.RI:

        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
            System.out.println("The serial port event is OUTPUT_BUFFER_EMPTY ");
            break;
        case SerialPortEvent.DATA_AVAILABLE:

            System.out.println("The serial port event is Data available ");
            byte[] readBuffer = new byte[20];
            System.out.println(event.getEventType());
            try {
                while (inputStream.available() > 0) {
                    int numBytes = inputStream.read(readBuffer);
                    System.out.print(new String(readBuffer, 0, numBytes, "us-ascii"));
                }
                System.out.print(new String(readBuffer));
            } catch (IOException e) {
                e.printStackTrace();
            }
            serialPort.close();
            break;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题在于阅读部分。我不得不使用getBytes将字符串转换为字节数组,因为有来自模块的字节流。然后我逐个打印

     public class TwoWaySerialComm {

     void connect( String portName ) throws Exception {
     CommPortIdentifier portIdentifier = CommPortIdentifier
      .getPortIdentifier( portName );
        if( portIdentifier.isCurrentlyOwned() ) {
  System.out.println( "Error: Port is currently in use" );
   } else {
  int timeout = 10000;
  CommPort commPort = portIdentifier.open( this.getClass().getName(), timeout );

  if( commPort instanceof SerialPort ) {
    SerialPort serialPort = ( SerialPort )commPort;
    serialPort.setSerialPortParams( 38400,
                                    SerialPort.DATABITS_8,
                                    SerialPort.STOPBITS_1,
                                    SerialPort.PARITY_NONE );

    InputStream in = serialPort.getInputStream();
    OutputStream outputStream = serialPort.getOutputStream();
    outputStream.write( 53 ); 
    outputStream.write( 1 ); 
    outputStream.write( 20 ); 
    outputStream.write( 0 ); 
    outputStream.write( 83 ); 




    CommPort port = serialPort;
    System.out.println( "Write done" );
    ( new Thread( new SerialReader( in,port  ) ) ).start();


  } else {
    System.out.println( "Error: Only serial ports are handled by this example." );
  }
}
  }


  public static class SerialReader implements Runnable {

    InputStream in;
    CommPort serialport;
    public SerialReader( InputStream in, CommPort port) {
      this.in = in;
      serialport = port;
    }

    public void run() {
      byte[] buffer = new byte[ 1024 ];
      int len = -1;

      try {
        while( ( len = this.in.read( buffer ) ) > -1 ) {

            String stringis= new String( buffer, 0, len,"ASCII" );
         //System.out.println( stringis );
         byte[] by_new = stringis.getBytes();
         System.out.println("the lenghth of byte array is "+ by_new.length);
         System.out.println( "The read is " );
         for(int i=0; i<by_new.length; i++) 

            System.out.printf( "%5s",by_new[i]);

         serialport.close();

        }
      } catch( IOException e ) {
        e.printStackTrace();
      }
      try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {System.out.println(e);}
    }
    }



  public static void main( String[] args ) {
    try {
      ( new TwoWaySerialComm() ).connect( "COM2" );

    } catch( Exception e ) {
      e.printStackTrace();
    }
  }
}