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

How do I write a sequence of bytes to a serial port in java

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

设备串口规格如下

DIR START CMD VALLO VALHI END

→ 53 1 4 0 83

← 53 1 4 0 83

← 53 27 斯洛伐克 83

交易由以下数据包序列定义

• → 软件发送请求包。

• ← 仪器发送响应数据包。

• ← 仪器发送状态包。

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

每次启动;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;
        }
    }
}

问题出在阅读部分。我必须使用 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();
    }
  }
}