Initialize and write to a serial portTag(s): IO

This is for JAVA application only (JDK1.1).

(Win)Initialization is done via the MODE.COM utility. Then to write, simply open a stream using the OS logical name attached to the serial port. You can use the same technique to print to the printer port (in this case the local name would be "LPTx:").

public class SerialTest {
 public static void main( String args[]) {
  Runtime rt = Runtime.getRuntime();
  Process p = null;
  String portname = "com1:";
  // for Win95 : c:\\windows\\command.com
  //             c:\\windows\\command\\mode.com   
  String cmd[] = {
   "c:\\winnt\\system32\\cmd.exe", "/c",
   "start", "/min",
   "c:\\winnt\\system32\\mode.com", portname,
   "baud=9600", "parity=n", "data=8",
   "stop=1", 
   };
  try {
   p = rt.exec( cmd );
   if( p.waitFor() != 0 ) {
    System.out.println("Error executing command: " + cmd );
    System.exit( -1 );
    }
   byte data[] = 
     "Writing a byte stream out of a serial port.".getBytes();
   FileOutputStream fos = new FileOutputStream( portname );
   BufferedOutputStream bos = new BufferedOutputStream( fos );
   fos.write( data, 0, data.length );
   fos.close();
   }
  catch( Exception e ) {
   e.printStackTrace();
   }
 }
}



If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2012
[ home ]