Serial Programming - upload.wikimedia....
Serial Programming - upload.wikimedia....
Serial Programming - upload.wikimedia....
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
JavaComm API<br />
6.2.4 Simple Data Transfer<br />
Simple Writing of Data<br />
Writing to a serial port is as simple as basic Java IO. However there are a couple of caveats<br />
to look out for if you are using the AT Hayes protocol:<br />
1. Don't use println (or other methods that automatically append "\n") on the OutputStream.<br />
The AT Hayes protocol for modems expects a "\r\n" as the delimiter<br />
(regardless of underlying operating system).<br />
2. After writing to the OutputStream, the InputStream buffer will contain a repeat of<br />
the command that was sent to it (with line feed), if the modem is set to echoing the<br />
command line, and another line feed (the answer to the "AT" command). So as part<br />
of the write operation make sure to clean the InputStream of this information (which<br />
can actually be used for error detection).<br />
3. When using a Reader/Writer (not a really good idea), at least set the character<br />
encoding to US-ASCII instead of using the platform's default encoding, which might<br />
or might not work.<br />
4. Since the main operation when using a modem is to transfer data unaltered, the<br />
communication with the modem should be handled via InputStream/OutputStream,<br />
and not a Reader/Writer.<br />
// Write to the output<br />
os.print("AT");<br />
os.print("\r\n"); // Append a carriage return with a line feed<br />
is.readLine(); // First read will contain the echoed command you<br />
sent to it. In this case: "AT"<br />
is.readLine(); // Second read will remove the extra line feed that<br />
AT generates as output<br />
Simple Reading of Data (Polling)<br />
If you correctly carried out the write operation (see above) then the read operation is as<br />
simple as one command:<br />
// Read the response<br />
String response = is.readLine(); // if you sent "AT" then response<br />
== "OK"<br />
Problems with the simple Reading / Writing<br />
The simple way of reading and/or writing from/to a serial port as demonstrated in the<br />
previous sections has serious drawbacks. Both activities are done with blocking I/O. That<br />
means, when there is<br />
• no data available for reading, or<br />
• the output buffer for writing is full (the device does not accept (any more) data),<br />
95