Read And Write in Serial Port Using Java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Daniar
 */

import java.io.*;
import java.util.*;
import javax.comm.*;
                                                                                                                                                                                                                                                                                                                                                                                                                                                 





public class SimpleRead implements Runnable, SerialPortEventListener {
////map the port names to CommPortIdentifiers
//this is the object that contains the opened port
    static CommPortIdentifier portId;
////for containing the ports that will be found
    static Enumeration portList;
//input for sending and receiving data
    static InputStream inputStream;
    static OutputStream outputStream;
    static SerialPort serialPort;
    static String messageString = "Hello, world!\n";
    Thread readThread;

 
    public static void main(String[]args) {
////just a boolean flag that i use for enabling
    //and disabling buttons depending on whether the program
    //is connected to a serial port or not
        boolean portFound = false;
        String defaultPort = "COM1";

  if (args.length > 0) {
   defaultPort = args[0];
}
 
portList = CommPortIdentifier.getPortIdentifiers();//mengambil port

while (portList.hasMoreElements()) {
   portId = (CommPortIdentifier) portList.nextElement();
   if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {//identifikasi serial port atau tidak
if (portId.getName().equals(defaultPort)) {
   System.out.println("Found port: "+defaultPort);
   portFound = true;
   SimpleRead reader = new SimpleRead();
                    try {
                        serialPort = (SerialPort)portId.open("SimpleWriteApp", 2000);
                    } catch (PortInUseException e){}
                    try {
                        outputStream = serialPort.getOutputStream();
                    } catch (IOException e) {}
                    try {
                            serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                    } catch (UnsupportedCommOperationException e) {}
                    try {
                        outputStream.write(messageString.getBytes());
                    } catch (IOException e) {}
                }
            }
        }
if (!portFound) {
   System.out.println("port " + defaultPort + " not found.");
}
 
    }

 
    public SimpleRead() {
try {
//objek serial port bs melemparkan ke portId
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);//time out 2000
} catch (PortInUseException e) {}

try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {}

try {
//memantau event yg terjadi pada serial port
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}

serialPort.notifyOnDataAvailable(true);//menerima pemberitahuan bila input data tersedia.biasa untuk asinkronus input

try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);//9600=kec aliran data per sec.set serial port parameter
} catch (UnsupportedCommOperationException e) {}

readThread = new Thread(this);

readThread.start();
    }

 
    public void run() {
try {
   Thread.sleep(20000);//sleep selama 20 detik
} catch (InterruptedException e) {}
    }


    public void serialEvent(SerialPortEvent event) {//data diterima
switch (event.getEventType()) {

case SerialPortEvent.BI:

case SerialPortEvent.OE:

case SerialPortEvent.FE:

case SerialPortEvent.PE:

case SerialPortEvent.CD:

case SerialPortEvent.CTS:

case SerialPortEvent.DSR:

case SerialPortEvent.RI:

case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
   break;

case SerialPortEvent.DATA_AVAILABLE:
   byte[] readBuffer = new byte[20];

   try {
while (inputStream.available() > 0)
{
   int numBytes = inputStream.read(readBuffer);
   System.out.print("The Read Bytes from SerialPort are");
   System.out.write(readBuffer);
   System.out.println();
}

System.out.print(new String(readBuffer));
   } catch (IOException e) {}

   break;
}
    }

}

Tidak ada komentar:

Posting Komentar

Adsense