通过java中的串口从输入流中读取字节

时间:2015-09-23 06:59:46

标签: java

我有一个通过串口发送的字节流。当发送所有字节时,我应该通过输入流再次接收字节流。

输出字节数组

byte[] command={(byte) 0xAA,0x55,0x05,0x00,0x55,(byte) 0xAA};

预期回复

**Serial command received
Admin Mode - IR Learn
In IR Learner Mode
Press IR Key...**

实际响应

**Serial command received
Admin Mode - IR Learn
In IR e - IR**

的InputStream

public void serialEvent(SerialPortEvent event) {
    try {

        Thread.sleep(100);

    } catch (InterruptedException e2) {
        e2.printStackTrace();
    }
    StringBuilder sb = new StringBuilder();

    try {
        int length = inputStream.available();
        readBuffer = new byte[length];

        Thread.sleep(110);


        while (inputStream.available() > 0) {
            int numBytes = inputStream.read(readBuffer);

            for (byte b : readBuffer) {

                sb.append(new String(new byte[]{b}));
            }
        }
        System.out.println(sb.toString());

        JOptionPane.showMessageDialog(contentPane, "Learned code : " + sb.toString(), "Code", JOptionPane.INFORMATION_MESSAGE);

    } catch (IOException e4) {
        e4.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    readBuffer = null;
}

的OutputStream

for (int i = 0; i < command.length; i++) {
    outputStream.write(command, 0, command.length);
    outputStream.flush();
}

如何在没有重复的情况下获得值JOptionPane

请帮忙

1 个答案:

答案 0 :(得分:0)

  1. 摆脱所有的睡眠。
  2. 您正在向StringBuffer.添加垃圾更改此内容:

    while (inputStream.available() > 0) 
    {
        int numBytes = inputStream.read(readBuffer);
        for (byte b:readBuffer)
        {
            sb.append(new String(new byte[] {b}));                                               
        }
    }
    

    到此:

    while (inputStream.available() > 0) 
    {
        int numBytes = inputStream.read(readBuffer);
        if (numBytes < 0)
            break;
        sb.append(new String(readBuffer, 0, numBytes));
    }
    
  3. 在输出端,您正在多次编写每个命令。改变这个:

    for(int i=0;i<command.length;i++)
    {
        outputStream.write(command,0,command.length);
        outputStream.flush();
    }
    

    到此:

    outputStream.write(command,0,command.length);
    outputStream.flush();