Write data in short using java

167 views Asked by At

I am trying write data into my serial port using java. For now I can only populate the data into a table form. Can I know are there any ways to write short data into the serial port.

This is my code:

    static short[] bytearray = {0x02, 0x08, 0x16, 0x00, 0x00, 0x33, 0xC6 , 0x1B};
    outputStream = serialPort.getOutputStream();
    outputStream.writeShort(bytearray);
    outputStream.flush();

I cannot use the write short at the outputstream write method. Can anyone help me with this. Thank you.

2

There are 2 answers

2
defectus On

As I understand it the writeShort takes as a parameter an integer and sends two shorts to the port. So all you have to do is to convert two shorts into an int and call the method with it.

outputStream = serialPort.getOutputStream();
for (int i = 0; i < bytearray.length; i+=2) {
   outputStream.writeShort((bytearray[i + 1] << 16) | bytearray[i]);
}
outputStream.flush();

Note that this code hasn't been tested - use as an inspiration only! Especially the bytearray[i + 1] bit can throw index out of bounds!

0
Dakshinamurthy Karra On

It should depend on who is reading the data you are writing to the serial port. If it is also a java program that you are developing, the easiest thing is to use a ObjectOutputStream to write your array of shorts and read it on the other side using an ObjectInputStream. On the other hand if the other side is a device, you need to worry about whether it accepts BigEndian or LittleEndian formats for the numbers. You can write a method to convert your array of shorts into a byte array and use OutputStream#write.