簡體   English   中英

如何將字節序列寫入java中的串行端口

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

我是java初學者。 我必須通過 com 端口向我正在使用的工具發送 5 個連續的整數。 我正在使用 rxtx 庫。 儀器不響應我的代碼。 我嘗試將值初始化為字符串,然后使用 getbytes 更改為字節。 但即使這樣也無濟於事。如果有人能幫助我,那將是一個很大的幫助。 該儀器在 COM5 處標識。 我嘗試首先寫入 Com 端口。 數據可用事件被觸發。 但是輸入流讀取的是無法識別的字符。 我認為問題在於寫入端口。 如果有人可以幫助我,那將是一個很大的幫助。

設備的串口規格如下

DIR START CMD VALLO VALHI END

→ 53 1 4 0 83

← 53 1 4 0 83

← 53 27 斯洛施 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;
        }
    }
}

問題是因為閱讀部分。 我必須使用 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();
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM