Thursday, January 1, 2009

The Powerful RConsole Class

The RConsole class is a very useful way of sending output from the nxt brick over a Bluetooth connection to the PC. Consider the following Java code, which runs on the brick. The class EOPDSensor reads the raw and processed values of the Electro Optical Proximity Detector (EOPD) available from HiTechnic and sends those sensor readings back to the console:


import lejos.nxt.Button;
import lejos.nxt.LCD;
import lejos.nxt.SensorPort;
import lejos.nxt.comm.*;
import lejos.nxt.addon.*;

public class EOPDSensor {

/**
* @param args
*/
public static void main(String[] args) {

RConsole.openBluetooth(40000);

LCD.drawString("Connected", 0, 2);

EOPD electroSensor = new EOPD(SensorPort.S1);

while(!Button.ESCAPE.isPressed()){
electroSensor.setModeLong();
RConsole.println(Integer.toString(
electroSensor.readRawValue()));
RConsole.println(Integer.toString(
electroSensor.processedValue()));

try{
Thread.sleep(5000);
}catch(InterruptedException e){
System.exit(0);
}
}

RConsole.println("Closing...");

RConsole.close();



}

}
The methods of the RConsole class are all static; the methods belong to the class and not to any instance of the class. So, the RConsole class should not be instantiated with the new keyword. The methods should be called in the form RConsole.method().

In the first line of the main method, RConsole waits 40 seconds (40,000 milliseconds) for the master (i.e the PC) to attempt to open a Bluetooth connection. Once the connection is established, the second and third lines of the while loop println the raw and processed values of the EOPD sensor, respectively. If the user presses the brick’s escape button, the tiny square gray button on the brick, the loop ends. The brick invokes the RConsole's close() method to close the Bluetooth connection.

To establish the connection in practice, do the following things. First, get to a command prompt on your PC. Next, run the Java program on the brick. Remember that the brick will wait only 40 seconds for the PC to attempt a connection. So, you must work quickly once the brick's Java program has started running.

At the PC’s command prompt, enter the command nxjconsole. Your PC will now go out and try to establish a connection with the brick. Once the connection is established, output similar to the following should appear.



To sum it up, the RConsole class is a very quick and easy way of getting output from your brick and onto your PC.

No comments: