28.12.2013 Views

Serial Programming - upload.wikimedia....

Serial Programming - upload.wikimedia....

Serial Programming - upload.wikimedia....

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

JavaComm API<br />

wantedPortName);<br />

System.exit(1);<br />

}<br />

//<br />

// Use port identifier for acquiring the port<br />

//<br />

...<br />

Note:<br />

JavaComm itself obtains the default list of available serial port identifiers from its<br />

platform-specific driver. The list is not really configurable via JavaComm. The method<br />

CommPortIdentifier.addPortName() is misleading, since driver classes are platform<br />

specific and their implementations are not part of the public API. Depending on the<br />

driver, the list of ports might be configurable / expendable in the driver. So if a particular<br />

port is not found in JavaComm, sometimes some fiddling with the driver can help.<br />

Once a port identifier has been found, it can be used to acquire the desired port:<br />

//<br />

// Use port identifier for acquiring the port<br />

//<br />

<strong>Serial</strong>Port port = null;<br />

try {<br />

port = (<strong>Serial</strong>Port) portId.open(<br />

"name", // Name of the application asking for the port<br />

10000 // Wait max. 10 sec. to acquire port<br />

);<br />

} catch(PortInUseException e) {<br />

System.err.println("Port already in use: " + e);<br />

System.exit(1);<br />

}<br />

//<br />

// Now we are granted exclusive access to the particular serial<br />

// port. We can configure it and obtain input and output streams.<br />

//<br />

...<br />

6.2.3 Initialize a <strong>Serial</strong> Port<br />

The initialization of a serial port is straight forward. Either individually set the communication<br />

preferences (baud rate, data bits, stop bits, parity) or set them all at once using the<br />

set<strong>Serial</strong>PortParams(...) convenience method.<br />

As part of the initialization process the Input and Output streams for communication will<br />

be configured in the example.<br />

import java.io.*;<br />

...<br />

//<br />

// Set all the params.<br />

93

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!