Java: serialport exception- port is busy

1.3k views Asked by At

I have a bill validator attached to PC through com port. I try to send data to bill validator and receive output (bill validator communicates through ccnet protocol ) here is my code -

public static void main(String[] args) throws SerialPortException {

    String s[]=SerialPortList.getPortNames();
    for (String x :s){
       System.out.print(x);
       SerialPort serialPort=new SerialPort(x);
    }

    try {
        SerialPort serialPort=new SerialPort("COM4");
        serialPort.openPort();
        serialPort.setParams(9600, 8, 1, SerialPort.PARITY_NONE);
        serialPort.writeString("RESET");
        serialPort.setEventsMask(SerialPort.MASK_RXCHAR);
        serialPort.addEventListener(new list());

        System.out.println(serialPort.readBytes(5));
    } catch (SerialPortException sex){
    System.out.print(sex);
    }

serial port event listener:

private  static class list implements SerialPortEventListener{

    @Override
    public void serialEvent(SerialPortEvent spe) {
        if (spe.isRXCHAR()&&spe.getEventValue()>0){
        try {

            String data =s erialPort.readString(spe.getEventValue());
        } catch (SerialPortException ex) {
        Logger.getLogger(Terminal.class.getName()).log(Level.SEVERE, null, ex);
        }
        }       
}

So I get serial port exception port is busy , how can i fix that ?

1

There are 1 answers

3
Pourya On

Mostly this will occur in 2 situations: 1- You have assigned a wrong port which maybe another device, you can check it through your device manager. 2- You have opened it previously with another software or maybe your previous run of code is still using it and you haven't terminate it. I see in your code you have first listed all your com ports but you don't benefit from it, it seems redundant. I recommend you delete all lines in your try part of your code and just leave the openport line and do it for other lines to see which line gives the exception.