Thursday, February 12, 2015

COM port in JAVA With Eclipse

In some cases we need to make programs which communicate with the COM port in the computer.
In here Com ports are normal USB ports.

So we have to add a library called RXTX.

To get that library you have to download the library from here.

And get the relevant library accrdoding to the your JDK.
Ex:- If your JDK is 64bit and Your OS is windows then download Windows-x64 library.



Open Eclipse and create a  new Project.

Create a new class called Test.

And add this code into it

import gnu.io.*;

import java.util.Enumeration;



public class Test {



public static void main(String[] args) {

   CommPortIdentifier serialPortId;
   Enumeration enumComm;

   enumComm = CommPortIdentifier.getPortIdentifiers();

   serialPortId = (CommPortIdentifier) enumComm.nextElement();
   System.out.println("Name "+serialPortId.getName()+" Type "+serialPortId.getPortType());
}
}


After You did that you can see error in import line.

 Open the zip file downloaded.

There is  3 files called
   RXTXcomm.jar
   rxtxParallel.dll
   rxtxSerial.dll

copy .dll files to your project's root folder.
             If you don't know where is the root folder then right click on the project name in left window.
             Select show in.
             Click system explorer.
             
             In here you can see the folder which named same as project name.
             Go in to it.
             Copy .dll files.

then create a folder in root folder called lib
Copy the  RXTXcomm.jar in to it.

Then in eclipse window right click in the project name click the refresh.

Right click in the project name and click properties.


In that window click the Libraries TAB.
Click add jars button.
Select the lib folder in it and select the RXTXcomm.jar
Press OK.



In Library window you can see the RXTXcomm.jar was added.
Click on its arrow.

Double Click native library location.
Now give the path to your root directory.

Errors will disappear.

Now we have to run our code.
Before that open device manager and click port section in the list.



It is for the verify program output.
Now run the code you will get the one of your COM port available.(Exactly the first port).


You can extend this code to get the all ports in the system.

No comments:

Post a Comment