javastringserial-portbytecomm

Send 'A' in the form of byte array to comm port using javaSerial port library


I am trying to send command to a boom barrier which is connected to 'COM1', it has baudrate -> 9600, parity -> none, data bits ->8, stop bits -> 1. I am trying the following code but unable to send the command. Please help me.

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

import com.fazecast.jSerialComm.SerialPort;

public class BoomBarrierUsingJavaSCLib {

    public static void main(String[] args) {
        SerialPort comPort = SerialPort.getCommPorts()[0];
        //System.out.println(SerialPort.getCommPorts().length);
        comPort.openPort();
        comPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 100, 0);

        comPort.setComPortTimeouts(1000, 1000, 1000);
        System.out.println("Written to Comport: "+comPort.writeBytes("A".getBytes(),"A".getBytes().length));
        comPort.closePort();
    }

}

but I am getting the following output: Written to Comport: -1 Ideally it should return the number of bytes written on the comm port. -1 indicates nothing is written to it.

Thanks in advance.


Solution

  • All I missed was, I did not close the bray++ terminal which was not allowing the comm port to open. While writing to port it is necessary to check that port is available.