rather pragmatic approach. (Guess why we’re using it?) Also, it doesn’t have
a lot of bells and whistles yet, but it runs on many platforms and works per-
fectly with the Arduino.
jSSC is completely self-contained—that is, you only need the
jssc.jar
file to get
started with your first project. Download the most current release and make
sure that
jssc.jar
is on your class path. Then enter the following code in your
favorite IDE or text editor:
SerialProgramming/Java/AnalogReader.java
import jssc.SerialPort;
import jssc.SerialPortList;
import jssc.SerialPortException;
public class AnalogReader {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println(
"You have to pass the name of a serial port."
);
System.exit(1);
}
try {
SerialPort serialPort = new SerialPort(args[0]);
serialPort.openPort();
Thread.sleep(2000);
serialPort.setParams(
SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE
);
while (true) {
serialPort.writeString("a0\n");
System.out.println(readLine(serialPort));
}
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
private static String readLine(SerialPort serialPort) throws Exception {
final int MAX_LINE = 10;
final byte NEWLINE = 10;
byte[] line = new byte[MAX_LINE];
int i = 0;
Appendix 3. Advanced Serial Programming • 260
report erratum • discuss
www.it-ebooks.info