Ng Zhong Qin
Ng Zhong Qin

Reputation: 1261

How to initialise a serial port using java?

I know this question has been asked many times and i've looked through the top 20 search result from google and i still cant get my code to work.

portList = CommPortIdentifier.getPortIdentifiers();
System.out.println("portList... " + portList);
while (portList.hasMoreElements()) {
    portId = (CommPortIdentifier) portList.nextElement();
    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        System.out.println("port identified is Serial.. "+ portId.getPortType());
        if (portId.getName().equals("COM2")) {
            System.out.println("port identified is COM2.. "+ portId.getName());  
            SimpleRead reader = new SimpleRead();
        } else {
            System.out.println("unable to open port");
        }
    }else{
        System.out.println("pordId.PortType = "+portId.getPortType());
        System.out.println("CommPortIdentifier.PORT_SERIAL = "+CommPortIdentifier.PORT_SERIAL);
    }
}

The output i'm getting is

run:

portList... javax.comm.CommPortEnumerator@18020cc BUILD SUCCESSFUL (total time: 0 seconds)

Does anyone know what is wrong? why doesnt portId have more elements? the program doesnt enter the while loop.

Thanks in advance for reading this post.

Upvotes: 4

Views: 1676

Answers (1)

Ng Zhong Qin
Ng Zhong Qin

Reputation: 1261

I managed to solve the problem. I need to copy the files into the following places for javac.comm to work

1) win32com.dll to directory : jdk1.7.0/bin
2) javax.comm.properties to directory : jdk1.7.0/jre/lib
3) comm.jar to directory : jdk1.7.0/lib

now the output is

portList... javax.comm.CommPortEnumerator@9173ef
port identified is Serial.. 1
port identified is CO11.. COM11
In SimpleRead() contructor
Serial Port.. COM11
Input Stream... com.sun.comm.Win32SerialInputStream@95c083
................
port identified is Serial.. 1
unable to open port
pordId.PortType = 2
CommPortIdentifier.PORT_SERIAL = 1
pordId.PortType = 2
CommPortIdentifier.PORT_SERIAL = 1
ending main
In run() function 

Upvotes: 2

Related Questions