Upload
others
View
0
Download
0
Embed Size (px)
Citation preview
Using NetBeans to create Java Robot Applications
Getting Started
Software Installation NetBeans can be downloaded free from:
http://netbeans.org/
You should download the Java SE version which is sufficient for basic Java development and
programming the robot.
You will also need to install the LeJOS Java robot API which can be obtained from:
http://lejos.sourceforge.net/
Make sure that you download the correct version for the NXT brick. This site also contains the
documentation for all of the classes and methods available. For the development of Java applications
which run and control the robot from the PC then you need the PC API documentation. A quick link to
this is:
http://lejos.sourceforge.net/nxt/pc/api/index.html
The software also includes the facilities to write code which can be downloaded and run on the robot
itself. If you wish to do this then consult the tutorials and forums on the LeJOS website where a lot of
information is provided. In this document we will be concentrating on code which will run on the PC and
control the robot via bluetooth.
When you install LeJOS it will automatically prompt you to install the LeJOS firmware on your robot
(assuming it is connected via the USB cable at the time of installation). If you need to repeat this at any
point in the future then go to the bin folder of the LeJOS installation directory and run nxjflashg.bat.
When you create a NetBeans project later in this document you will require three library files from the
installation folder of LeJOS on your PC. These can be found in the following locations (assuming you
installed LeJOS to the default location):
C:\Program Files\leJOS NXJ\lib\pccomm.jar
C:\Program Files\leJOS NXJ\lib\pctools.jar
C:\Program Files\leJOS NXJ\3rdparty\lib\bluecove.jar
NetBeans/Java Tutorials A number of useful tutorials are included on the NetBeans site in the “Docs & Support” area. In
particular you may wish to try:
http://netbeans.org/kb/docs/java/quickstart.html (simple command line program)
http://netbeans.org/kb/docs/java/gui-functionality.html (basic form application)
NetBeans Project Configuration
Creating a New Project Open NetBeans, select File/New Project and select “Java Desktop Application”
Press Next
Choose a project name and location (defaults can be left for other options but note that “set as main
project” checked will make this the default project to run)
Press Finish
This will create the files necessary for a Java application containing a single form. Code edits to the form
will be placed in the View file (e.g. for the project TouchTest this will be the file TouchTestView.java) and
by default this file will be open in Design mode. To edit the code itself press the Source tab above the
form.
Adding the Libraries for Connection to the Robot From outside NetBeans add a new folder within the project folder structure (it is recommended you call
this folder lib) and place the following library files in it:
pctools.jar bluecove.jar pccomm.jar
This will give you the following directory structure:
You must now add these libraries to the project itself. In NetBeans right-click on the project folder and
select “properties” to bring up the project properties window and select “libraries” on the left hand side
of the window. This enables you to add the required external libraries to your project.
Press “Add JAR/Folder” and browse to the folder you just placed the three libraries in. Select the library
files, ensure that “Reference as – Relative Path” is checked (this ensures that if you move the project
folder to a different machine the library files can still be referenced) and press Open.
The three libraries will now be referenced by your Java code and methods within them will be
recognized. Press OK to close the properties window.
Creating Form Controls and Handling Events Controls are added from the palette on the right-hand side of the screen and properties set below in the
same way as Visual Studio.
You may find it useful to rename your form control to something appropriate to its purpose. Unlike C#,
setting the “name” property does not rename the variables used in the code. You should therefore
rename controls by right-clicking on them and selecting “Rename variable”.
To add an event handler (e.g. for a button) you should double-click on the control. This will firstly display
the “set action” window. If you wish to create a new action handler (rather than call an existing one)
then select “Create new action” in the action box and accept the default class in which to place the code
(this will be the form class). Choose a name for your event handler and type this into the “Action’s
Method” box.
Press OK to create the method and you will be taken to code view ready to type your Java code.
Running the Application To run the current project (this is the one with its name highlighted in bold in the project explorer) press
the green arrow on the top toolbar. If the required project is not the currently highlighted one, then
right-click on the project name and select run.
To set a project as the default project to run when the green arrow is pressed right-click on the required
project and select “Set as Main project”.
When you run the project it will attempt to connect to a robot which is in range. You may find the first
time you run that it takes a long time and continues seeking for multiple robots. If this happens then
interrupt the program by selecting “Run/Stop build/run” and start it off running again. This is also a
useful command if your program ever stops responding or you need to interrupt it. If you do this while it
is connected to your robot then it is recommended that you also power the robot off and on again in
case it has been left in a “strange” state.
Running the Application from outside NetBeans To run a Java program from outside a Java environment then you need to create an Executable Jar file.
This can be done by pressing the “hammer” icon to the left of the run arrow (for the current project) or
right-clicking on the required project and selecting “Build” or “Clean and Build”
This will create a folder within your project called “dist”, which will contain the Jar file and any libraries
required. You can then run the application by double-clicking on the Jar file. Note that if you move the
location of this file, you must also move the library sub-folder. Also, any machine which you wish to run
the application on must have the Java Runtime Environment installed.
Java Coding
Importing External Java Classes Before using Java NXT classes (or other external libraries) you must add an import statement for each to
the top of your code. The LeJOS documentation will indicate which import statements are required for a
particular class. For example, the following import statements would be required for a robot which
included navigation using the pilot class:
import lejos.nxt.*;
import lejos.robotics.navigation.*;
Instance Variables If you wish to add additional instance variables (form variables which are available to all methods in
your class) then these should be added at the bottom of the code file (in NetBeans this is where the
code-generated instance variables are located so it is more consistent to place your instance variables
with them). For example:
private TachoPilot pilot;
Initialisation and Creation of Objects Initialisation of instance variables and creation of objects to be used throughout the form would
normally be done within the constructor. In a Java forms application the constructor (the first method in
the class, having the same name as the class) contains a lot of automatically generated code. You
shouldn’t edit or delete any of this code and should place any statements of your own at the end of the
auto-generated code. It may be easier to manage and locate your code in the future if you create your
own additional method containing your initialisation and simply add a single line to the end of the
constructor which calls your method. For example:
Auto-generated code
Custom initialization method
Call custom initialisation
Navigation A wheeled robot can be controlled accurately using the TachoPilot class. There are a large number of
methods available within this class so it is recommended you consult the documentation for more
details but the example below demonstrates basic motion in getting the robot to move in a square.
In order to use the TachoPilot class an additional import statement is required:
import lejos.robotics.navigation.*;
An instance variable is required and the object must be created (usually done within the constructor or
your own initialisation method):
private TachoPilot pilot;
pilot = new TachoPilot(2.1f, 4.4f, Motor.A, Motor.C, true);
The two floating point parameters here refer to the diameter of the wheels (2.1 in for the Tribot) and
the wheelbase of the robot (4.4 in for the Tribot).
The code below sets the movement and turning speeds (see below) of the robot and then moves it in a
square:
pilot.setMoveSpeed(3); pilot.setTurnSpeed(20); for (int i=0; i< 4; i++) { pilot.travel(-12); pilot.rotate(90); } Note that negative values are passed to the travel method. The reason for this is that the standard
Tribot configuration has the motors attached in such a way that they move in the reverse direction to
travel forwards so all values are reversed (to move backwards then a positive value is required).
To move the robot continuously (until it is stopped by the user) then the following commands can be
used:
pilot.backward(); pilot.forward(); pilot.stop();
Again note that for our Tribot backward is required to move forwards and forward is required to move
backwards!!
The speed of the robot depends on the motor power available and this can be dependent on the
battery. The maximum speed values available can be obtained using the following functions:
float fMaxMoveSpeed = pilot.getMoveMaxSpeed();
float fMaxTurnSpeed = pilot.getTurnMaxSpeed();
As an example, the Tribot used in this example has a maximum movement speed of approximately 14
and a maximum turning speed of approximately 300, hence the difference in scale of the values used
above (this robot actually moves faster than it turns!).
Adding a Timer In NetBeans there is no form control for a timer. Instead you need to create one within code and create
a method which will be executed on each “tick” of the timer. The easiest way to do this is using
something complicated called an “inner class”. Don’t worry about understanding how this works as the
code is reasonably simple and if you follow the example below (which adds a timer to monitor the touch
sensor) this should be easily adapted to any purpose.
Step 1
Create an instance variable for your timer (in this example an instance variable for the touch sensor is
also created):
private Timer touchTimer; private TouchSensor touchSensor;
Step 2
In your initialization method (as described above) create the timer object, set the timer interval (in this
case 50 milliseconds) and add an actionPerformed event. This is the code that will be run whenever the
timer “ticks”. In this case we set the actionPerformed event to call another method touchTimerTick()
where we write the actual code to be executed.
private void robotInitialise() { touchSensor = new TouchSensor(SensorPort.S1); // create the touch timer touchTimer = new Timer(50, new ActionListener() { public void actionPerformed(ActionEvent e) { touchTimerTick(); } }); }
Step 3
Write the method which is called from the actionPerformed event. In this example this checks the status
of the touch sensor and writes an appropriate string to a label on the form.
private void touchTimerTick() { if (touchSensor.isPressed()) { jlblStatus.setText("Touch Sensor Pressed"); } else { jlblStatus.setText("Touch Sensor Not Pressed"); } }
Step 4
By default the timer is not running so to start and stop it you need to write the appropriate code in
other event handlers (or wherever you wish to start/stop your timer). In this example we have provided
two button handlers so that the user can choose when to start and stop monitoring the sensor:
@Action public void startButtonClick() { touchTimer.start(); } @Action public void stopButtonStop() { touchTimer.stop(); jlblStatus.setText("Not Recording"); }
Providing a simple Message Box You may wish to provide a simple message box to the user, such as to display an error message. This can
be done using a JOptionPane. This requires an additional import statement:
import javax.swing.JOptionPane;
A message box can then be provided using the following code:
JOptionPane.showMessageDialog(null, "Message");
Or with a title and message type:
JOptionPane.showMessageDialog(null, "Message", "Title", JOptionPane.ERROR_MESSAGE);
Adding a Pause to your Code In some situations you may wish to add a pause to your code to allow time for something to happen on
the robot before continuing with code execution. One such example is that when polling the ultrasonic
sensor it is recommended that you pause for at least 25ms before checking the distance value (to allow
the ultrasonic wave time to return).
The Java code to do this makes use of the Thread.sleep command and (as in C#) this requires exception
handling to be provided. The example below shows this in action, using a JOptionPane to provide a
message to the user and return from the event handler immediately if an exception occurs:
//include a 25ms delay to pick up values try { Thread.sleep(25); } catch(Exception e) { JOptionPane.showMessageDialog(null, "Error obtaining ultrasonic data"); return; }
The Ultrasonic Sensor The ultrasonic sensor is created in the same way as a touch sensor by connecting it to the appropriate
port. To obtain the distance value the sensor should be “pinged”, a 25ms delay (or more) should be
made and then the value can be obtained. The following code uses a timer to repeatedly obtain values
from the ultrasonic sensor and write the result to a form lable:
public void ultrasonicTimerTick() { int iDist; // ping the sensor ultrasonicSensor.ping(); //include a 25ms delay to pick up values try { Thread.sleep(25); } catch(Exception e) { JOptionPane.showMessageDialog(null, "Error obtaining ultrasonic data"); return;
} // obtain the sensor reading and display on form iDist = ultrasonicSensor.getDistance(); jlblUltrasonic.setText(Integer.toString(iDist)); }