2
votes

I have a stream of bytes to be sent through a serial port. When all the bytes are sent I should receive a stream of bytes again through the inputstream.

Output Byte Array

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

Expected Response

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

Actual Response

**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();
}

How can I get the value without the repetition and JOptionPane?

Please help

1

1 Answers

0
votes
  1. Get rid of all the sleeps.
  2. You're adding junk to the StringBuffer. Change this:

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

    to this:

    while (inputStream.available() > 0) 
    {
        int numBytes = inputStream.read(readBuffer);
        if (numBytes < 0)
            break;
        sb.append(new String(readBuffer, 0, numBytes));
    }
    
  3. On the output side, you're writing every command several times. Change this:

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

    to this:

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