Cara membaca data dari port serial pada java adalah dengan menambahkan library rx tx caranya :
- Download library rxtx pada link berikut : http://rxtx.qbang.org/pub/rxtx/rxtx-2.1-7-bins-r2.zip
- Extract file rxtx-2.1-7-bins-r2.zip
- Copy file bernama RXTXcomm.jar ke C:\Program Files\Java\jdk1.7.0_04\jre\lib
- Copy file bernama rxtx-2.1-7-bins-r2\Windows\i368-mingw32\rxtxSerial.dll ke C:\Program Files\Java\jdk1.7.0_04\jre\bin
- Source Code on NetBeans IDE 7.1 :
import gnu.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;
public class RFID implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
byte[] readBuffer;
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
System.out.println("portList... " + portList);
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL){
if (portId.getName().equals("COM1")){
System.out.println("port identified is "+ portId.getName());
RFID reader = new RFID();
} else {
System.out.println("Unable to open port");
}
}
}
public RFID() {
try {
System.out.println("Initialitation Port");
serialPort = (SerialPort) portId.open("COM1",500);
System.out.println(" Serial Port.. " + serialPort);
} catch (PortInUseException e) {
System.out.println("Exception in Initialitation Port");
}
try {
inputStream = serialPort.getInputStream();
System.out.println("Initialitation Input Stream");
} catch (IOException e) {
System.out.println("Exception in Input Stream");
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
System.out.println("Too many Listener exception");
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
System.out.println("Inisialitation Baudrate");
} catch (UnsupportedCommOperationException e) {
System.out.println("Not supported operation");
}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
System.out.println("Run...");
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Exception in run");
}
}
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
readBuffer = new byte[8];
try {
while (inputStream.available()>0) {
int numBytes = inputStream.read(readBuffer);
System.out.print(new String(readBuffer));
}
} catch (Throwable ex) {
System.out.println("Hardware Disconnected");
System.exit(0);
}
break;
}
}
}