External Interfaces Previous page   Next Page

Example - Communicating Through a Serial Port

The serialexample program uses classes of the Java API javax.comm package, which support access to communications ports. After defining port configuration variables, serialexample constructs a javax.comm.CommPortIdentifier object, to manage the serial communications port. The program calls the open method on that object to return an object of the javax.comm.SerialPort class, which describes the low-level interface to the COM1 serial port, assumed to be connected to a Tektronix oscilloscope. (The example can be run without an oscilloscope.) The serialexample program then calls several methods on the SerialPort object to configure the serial port.

The serialexample program uses the I/O package java.io, to write to and read from the serial port. It calls a static method to return an OutputStream object for the serial port. It then passes that object to the constructor for java.io.OutputStreamWriter. It calls the write method on the OutputStreamWriter object to write a command to the serial port, which sets the contrast on the oscilloscope. It calls write again to write a command that checks the contrast. It then constructs an object of the java.io.InputStreamWriter class to read from the serial port.

It calls another static method on the SerialPort object to return an OutputStream object for the serial port. It calls a method on that object to get the number of bytes to read from the port. It passes the InputStream object to the constructor for java.io.OutputStreamWriter. Then, if there is data to read, it calls the read method on the OutputStreamWriter object to read the contrast data returned by the oscilloscope.

Setting Up the Java Environment

Before beginning to run this example, follow the procedure described here to set up your Java environment:

  1. Download the Java class javax.comm to a local directory. You can download this class from

http://java.sun.com/products/javacomm/downloads/index.html

  1. Add the Java class to your Java class path in MATLAB. See Finding and Editing classpath.txt.
  1. For example, if you downloaded the package to $MATLAB/work/javax, where $MATLAB is your MATLAB root directory, you would need to add the following entry to classpath.txt:

  1. Copy the file win32com.dll from the commapi directory into $MATLAB\sys\java\jre\win32\jre1.4.2\bin.
  2. Copy the file comm.jar from the commapi directory into $MATLAB\sys\java\jre\win32\jre1.4.2\lib\ext.
  3. Copy the file javax.comm.properties from the commapi directory into $MATLAB7\sys\java\jre\win32\jre1.4.2\lib.
  4. Exit and then restart MATLAB.

Previous page  Example - Finding an Internet Protocol Address Description of Serial Example Next page

© 1994-2005 The MathWorks, Inc.