Download repeat - Gammelgaardsskolen
Transcript
www.it-ebooks.info S ERIAL C OMMUNICATION U SING VARIOUS P ROGRAMMING L ANGUAGES This file defines two classes named AnalogReader and AnalogReaderTest. AnalogReader actually encapsulates access to the Arduino. It stores an InputStream object in _input to receive data, and it stores an OutputStream object in _output to send data to the Arduino. The constructor initializes the serial port connection and assigns its input and output streams to our member variables. To obtain a serial port connection, we have to get a CommPortIdentifier object first. From this object, we can then create a SerialPort object. This object gives us access to the underlying streams, and it also allows us to set the port’s parameters, such as the baud rate. We implement the protocol for our Arduino sketch in the run( ) method. There we wait for two seconds, and then we start a loop. In the loop, we send the string “a0” to the serial port using OutputStream’s write( ) method. Before we send the string, we turn it into a byte array calling getBytes( ). To give the Arduino some time to create a result, we wait for another 100 milliseconds. Afterward, we check if a result is available and read it by invoking InputStream’s read( ) method. AnalogReaderTest is only a small driver class that implements a main( ) method, creates an AnalogReader object, and calls run( ) on it. Here’s how to compile and use the program: maik> javac AnalogReaderTest.java maik> java AnalogReaderTest /dev/tty.usbmodemfa141 Experimental: JNI_OnLoad called. Stable Library ========================================= Native lib Version = RXTX-2.1-7 Java lib Version = RXTX-2.1-7 a0: 496 a0: 433 a0: 328 a0: 328 ^C After some debug output from the libraries we are using, the AnalogReaderTest does exactly what it’s intended to do: it permanently prints the values of the analog pin 0. Accessing a serial port in Java is a piece of cake if you use the right libraries. Ruby Even dynamic languages such as Ruby give you instant access to your computer’s serial port and to an Arduino if you connect it to it. But before that, you need to install the serialport gem: Report erratum this copy is (P1.0 printing, Janurary, 2011) 261