J/Link Tutorial: Communicating with the Serial Port
 | Download
this example as a
Mathematica
notebook. |
With the release of J/Link, almost all the capabilities of Java are now available directly from Mathematica. Now you can perform many tasks that used to require writing a MathLink program by simply loading the appropriate classes.
Communication with the serial port in Java is handled by a standard extension package for Java called
javax.comm, otherwise known as the Java Communications API. This functionality is not yet part of the standard Java 2 platform, although it is a standard extension. Implementations are freely available for Solaris, Windows, and various Unix platforms. Most other platforms will soon be supported.
To use J/Link to control a serial port, all you need to do is use the classes and methods that are available from the Java Communications API. Note that J/Link neither has nor requires any special knowledge about these Java classes. It works this way with any Java class.
Load J/Link and start the connection.
![[Graphics:Images/index_gr_1.gif]](http://library.wolfram.com/examples/JavaSerial/Images/index_gr_1.gif)
![[Graphics:Images/index_gr_2.gif]](http://library.wolfram.com/examples/JavaSerial/Images/index_gr_2.gif)
Load one class to start.
![[Graphics:Images/index_gr_3.gif]](http://library.wolfram.com/examples/JavaSerial/Images/index_gr_3.gif)
The next command gets the port object from the serial port COM1 on a Windows computer. On a UNIX machine you would, for example, replace COM1 with /dev/modem.
![[Graphics:Images/index_gr_4.gif]](http://library.wolfram.com/examples/JavaSerial/Images/index_gr_4.gif)
![[Graphics:Images/index_gr_5.gif]](http://library.wolfram.com/examples/JavaSerial/Images/index_gr_5.gif)
![[Graphics:Images/index_gr_6.gif]](http://library.wolfram.com/examples/JavaSerial/Images/index_gr_6.gif)
![[Graphics:Images/index_gr_7.gif]](http://library.wolfram.com/examples/JavaSerial/Images/index_gr_7.gif)
Now the serial port can be accessed directly from Mathematica.
![[Graphics:Images/index_gr_8.gif]](http://library.wolfram.com/examples/JavaSerial/Images/index_gr_8.gif)
![[Graphics:Images/index_gr_9.gif]](http://library.wolfram.com/examples/JavaSerial/Images/index_gr_9.gif)
![[Graphics:Images/index_gr_10.gif]](http://library.wolfram.com/examples/JavaSerial/Images/index_gr_10.gif)
Here is how you could write a command to the port.
![[Graphics:Images/index_gr_11.gif]](http://library.wolfram.com/examples/JavaSerial/Images/index_gr_11.gif)
![[Graphics:Images/index_gr_12.gif]](http://library.wolfram.com/examples/JavaSerial/Images/index_gr_12.gif)
That's it. You now
have a full, interpreted scripting environment for experimenting with or
programming the serial port in a completely portable way. Reading from the
port is handled by CommPort.getInputStream().read(). For more
information on common questions, please refer to the Javatm
Communications API FAQ.
Note that this example requires version 1.0.1 of J/Link.
|