Write to a COM port using Java program

By: Steven Lim Printer Friendly Format    


Most projects that deal with hardware and devices, needs to communicate with them using the COM port of the PC or Server. For example if there is a modem that is connected to a server via its COM port and the Java program has to send some AT commands to the modem then the Java program has to write to the COM port.

This sample Java program can be used to Write to a COM port. Note that you will need to change the Port number to COM1 or COM2 or any other ports as required.

Also if you are using unix based machines then you will have to uncomment the /dev/term/a instead of COM. You can also set the serial connection parameters such as the baud rate etc based on the device that you are connecting to.

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

public class SimpleWrite {
    static Enumeration portList;
    static CommPortIdentifier portId;
    static String messageString = "";
    static SerialPort serialPort;
    static OutputStream outputStream;

    public static void main(String[] args) throws IOException{
        portList = CommPortIdentifier.getPortIdentifiers();
		int i;
        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                 if (portId.getName().equals("COM1")) {
               // if (portId.getName().equals("/dev/term/a")) {
			while(( i=System.in.read()) != 13) 				
			messageString += (char)i; 		           
		try {
                        serialPort = (SerialPort)
                            portId.open("SimpleWriteApp", 2000);
                    } catch (PortInUseException e) {System.out.println(e);}
                    try {
                        outputStream = serialPort.getOutputStream();
                    } catch (IOException e) {System.out.println(e);}
                    try {
                        serialPort.setSerialPortParams(9600,
                            SerialPort.DATABITS_8,
                            SerialPort.STOPBITS_1,
                            SerialPort.PARITY_NONE);
                    } catch (UnsupportedCommOperationException e) {System.out.println(e);}
                    try { 				System.out.println(messageString);
                        outputStream.write(messageString.getBytes());
                    } catch (IOException e) {System.out.println(e);} 			
                }
            }
        }
    }
}


Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial