Java

Overview: 
Explore how to drive in arcs or smooth turns. Explore the use of a sensor to control robot behavior.
Objectives: 

Understand how to turn the robot when driving in an arc by making your robot drive in a circle. Understand how to use a simple sensor to control robot behavior.

Content: 

Now lets look at an example that drives the robot in a circle. The key idea here is that if you drive the motors in the same direction but at different power levels (speeds) the robot will drive in an arc and if it runs long enough that arc becomes a circle.

We are going to add a new hardware element to this exercise. We will use a touch sensor to determine when to stop driving.

Create a new  Java class file called DriveCircle in the ev3.exercises package, as we have for the previous exercises. Copy the code below to the class file:

The first thing to notice is that we set the motor powers to different levels. This will cause the robot to drive in an arc. You may need to adjust the power to get that arc to be a circle.

Next, we use a while loop let the motors run until the touch sensor is touched. We plug the sensor into sensor port 1. Reading a sensor requires several objects and multiple steps. We will put those steps in a private method to make the code easier to read and to keep the while statement comparison simple. In leJOS, sensors are accessed though an object representing that sensor, like the EV3TouchSensor object instance called sensor1 in our example.

The EV3 has 4 sensor ports numbered 1-4. When you create sensor object you tell the object which sensor port the sensor is connected to by specifying the port on the sensor object constructor. The leJOS API provides an enum called SensorPort with members that specify the port number to use.

The sensor object returns a SampleProvider object which is used to read values from the sensor. Data read from sensors is returned as an array of floating point numbers using the SampleProvider.fetchSample() method. An array is a variable that represents a list of numbers or strings or objects. Touch sensors return a single floating point number, 0 = not touched 1 = touched. The SampleProvider object tells us how big the array of floats needs to be for the number of results that fetchSampe() will return for the particular sensor. We create an array of floats of that size to receive the results of the fetchSample() method. We know all this from reading the documentation for the EV3TouchSensor.

The isTouched() method shows an example of passing a variable from the calling code to the called method (called an argument), the reference (touchSP) to the SampleProvider instance in our case. The isTouched() method fetches the sample value from the touch sensor each time we call it and returns true or false depending on the value of the sample returned in the first position (0) of the array of floats returned by fetchSample().

Finally, the variables SensorPort and MotorPort are variables defined by leJOS for you to use to identify sensor and motor ports. These variables are of the enum or enumeration type. Enums are used to assign meaningful names to a list of numeric values. You can read more about enums here.

Note that when you type the name of any variable, if that variable is a data type that has methods or internal items, you can type the name of the variable followed by a . (dot) and stop. Eclipse will display a list of the items available for the variable. You can then select an item on the list to complete the reference. Documentation, if available, is shown for the items in the list.

 

Navigation:

Overview: 
Explore how to connect to the EV3 over WiFi or Bluetooth instead of USB cable.
Objectives: 

Understand how to set up and connect to the EV3 over WiFi or Bluetooth connection instead of USB cable. Understand how to deploy code or access the EV3 with the EV3 Control Center tool over WiFi or Bluetooth.

Content: 

So far we have been deploying code to the EV3 over a USB cable connecting the EV3 to the development PC. This works fine but is tedious, time consuming and may mean moving the robot closer to the PC. A much better way to do development is to connect the EV3 and PC over WiFi (wireless network) or Bluetooth (wireless peer-to-peer).

Using WiFi assumes you have a WiFi router or access point available that your PC connects to. If so, you can purchase a USB based WiFi card for the EV3. The WiFi card to use is the Edimax EW-7811UN. You insert the card into the USB slot on the side of the EV3 next to the SD card slot.

Insert the card and turn on the EV3. When the EV3 menu appears, scroll right until the WiFi menu is in the center and press enter.  A list of WiFi access points should appear. Select your access point and press enter. A simulated keyboard will appear on the EV3 screen and you use it to enter the WiFi password for your access point. The letters U l x D appear at the bottom of the keyboard. They select U = upper case, l = lower case, x = delete and D = done. When you have entered the password select D for done. The network connection will be restarted and if the EV3 successfully connects to the network, when you return to the menu you will see two IP addresses below the EV3's name (EV3 by default). The second IP address is the WiFi address assigned by your access point. You should also assign the EV3 a unique name with the change name function on the System menu.

Note: that you can also use the EV3 Control Center (connected with USB cable) to configure the WiFi connection and assign the EV3 name (Tools tab, change friendly name). This is easier than using the EV3 LCD.

When done with these steps, go into Eclipse, Windows, Preferences, leJOS EV3. Select Connect to Named Brick and enter the name you assigned to the EV3.

Now when you deploy code in Eclipse, Eclipse will automatically connect to your EV3 over the network and download your program.

Note: If you have the USB WiFi card inserted in the EV3, deployment over a USB cable will likely not work. If the USB WiFi card is in contact with an access point and has been assigned an IP address by that access point, deployments will use the that access point address, not the 10.0.1.1 address used by USB even if your PC is disconnected from the access point. To return to using the USB cable, you must shutdown your EV3 and remove the WiFi card. Restart the EV3 and USB deployment will work. To return to using WiFi, shutdown the EV3 and reinsert the WiFi card and power up.

Bluetooth communication is built into the EV3. Here is a how-to to get connected (paired) to an EV3. Once you have paired with an EV3, when you deploy code in Eclipse, Eclipse will automatically connect to your EV3 over the network and download your program.

 

 

Navigation:

Overview: 
Explore the EV3 Control Center tool.
Objectives: 

Understand how to use the EV3 Control Center to explore and manipulate the EV3 without a program.

Content: 

The EV3 Control Center is installed with the leJOS SDK on your development PC. The Control Center is a powerful tool that allows you to view and control many aspects of the EV3 controller. With the EV3 connected to your PC, you can start the Control Center from the leJOS pull down menu on the Eclipse tool bar. You can also start Control Center by clicking on this file:

C:\Program Files\leJOS EV3\bin\ev3control.bat

You might want to create a desktop shortcut for that file as you will probably use Control Center often.

Control Center allows you to see the programs and files present on the EV3, allows you see the console (and keeps a record of what is displayed), allows you to remotely push the buttons on the EV3, start and stop programs, look at sensor values and control motors. In short, the Control Center is a very powerful and useful utility to get familiar with.

With your EV3 connected to your development PC, start Control Center. In the name box you can type the name you assigned to your EV3 and click connect, or you click search to have Control Center find your EV3 for you. 

Note that the Control Center has a few quirks. If the connect to an EV3 fails, there is no error message. The Connect button will change back to the unpressed state and that is all that happens. At the same time, when the connect is successful, the Control Center may not give any indication that it has connected. You will need to click on one of the tabs to see if it updates the displays.

Start the Control Center and connect to your EV3 and take some time to explore what Control Center offers.

 

Navigation:

Overview: 
Learn how to drive the EV3 robot in a square pattern by programming only two moves.
Objectives: 

Understand how to drive the EV3 robot is a square pattern. This involves turning and making 8 moves (4 straight and 4 turns) by programming only 2.

Content: 

Now lets try something more difficult. Lets write a program to drive your robot in a square pattern. This requires 8 moves: drive straight for some amount of time, turn, drive straight, turn, drive straight, turn, drive strait, turn. Lets use the Java for loop to program only 2 moves, drive straight and turn but then repeat those two moves to get the total driving moves we need.

Select the package ev3.exercises. Right-click and create a Java class called DriveSquare then copy and paste the code below into that class:

In this exercise we use the for loop to execute the two moves 4 times to drive the robot in a square.

Note that the two driving "moves" which we defined as "drive straight" and "turn", consist of starting the motors, waiting some amount of time then stopping the motors.

Note that we said turn right so we reversed motorA to make the turn. Which motor you reverse depends on how you wired your robot and which end you consider the "front". You will need to make some adjustments to the code to make the robot move correctly for your design.

Also note that the time to run the motors when making the turn may need to be adjusted to get good 90 degree turns. We reverse one motor and drive the other motor forward to make the robot turn in place or pivot to make a nice square. Later you will learn how to make accurate turns uding a gyro or the Regulated Motor's tachometer feature. 

Can you modify the code to make the turns rounded?

Finally, when the square is done, the robot turns one more time to it's original heading. This is because we execute the turn 4 times when you really only need 3 turns to complete the square. Can you modify the code to not make the extra turn?

One last thing. When you put this code into Eclipse, an error indication will appear on the for statement. Can you figure out what is wrong and fix it? Review the lesson on the for statement if needed.

 

Navigation:

Overview: 
Explore how to write a Java program to drive a simple EV3 robot forward and stop.
Objectives: 

Understand how to create a new project, the add a package to that project and then create a Java program in that package that will drive a simple EV3 robot forward and then stop.

Content: 

Now its time write more interesting Java programs for the EV3. Start Eclipse on your PC. When Eclipse is ready, the EV3 Exercises project you created in the HelloWorld lesson should appear in the project explorer on the left side of the screen.

Click on the project to open the project's tree of folders. One will be src, which is the directory where the project source files are stored. Right click on src and select New and then Package. This will display the New Package dialog. Enter the package name ev3.exercises. We are going to put each of our exercise (sample) programs into this package. This organizes all of the exercises in a single package. This is a simpler and more tidy way to organize things rather than have a separate project for each exercise.

The new package will appear under src in the project tree. Right-click the package and select New, Class. On  the New Class dialog, enter DriveForward for the class name. Check the box to create a static void main method stub. Click Finish. This will create the DriveForward.java file with the new class in it and open that class file in the editing area. You are ready to program!

Here is the Java code we will be working with. Select and copy the code below and replace the code in the DriveForward.java file completely.

Lets look at this code in detail:
 
First we see the package statement that puts our class into the package we created.
 
Next we see some import statements importing classes from the leJOS API hardware namespace. These classes will give us access to the EV3 and attached devices.
 
Next we display some information on the EV3 LCD panel that will show when our program is ready to run. We also use the Button class to use the LED lights that surround the EV3 buttons to flash the LEDs green when we are ready to drive. The Button class has a lot of methods that give us access to all of the EV3 buttons and the LEDs. Note that when using the println method, if the characters \n appear in the message, they generate a new line (or carriage return) request and the following text will start on the next line down.
 
Next we use the Sound class to control the EV3 speaker. Here we call a method that generates a series of rising tones to let you know when the program is ready to drive.
 
Next we use another Button class method to wait for any button to be pressed to start the driving portion of the program.
 
Once a button  is pressed, we create two UnregulatedMotor objects, one for each motor on our robot. An UnregulatedMotor is a simple motor that you control by setting the power level, 0-100%. The RegulatedMotor class is a more complex but more powerful way to control motors and we will explore it later.
 
There are 4 motor control ports or connections on the EV3. When you create a motor object to control a motor you indicate which port the motor is plugged into in the motor object constructor. LeJOS provides an enum called MotorPort with members A, B, C and D corresponding to the EV3 motor ports.
 
We then set the two motor objects to 50% power. The motors will start turning. Now we wait for 2 seconds (2000 milliseconds) allowing the robot to drive forward and then set the motors to 0% power. Setting power to zero causes the motors to stop with a braking effect so the stop is quick and the motors will resist movement. You can also call a method on the motor objects that cause them to coast or float leading to a gentler stop and the motors will not resist movement.
 
Finally we free the motor objects by closing them and generate a sound that is several tones descending to signal that the program  is done.
 
Once you have the code copied into the file in Eclipse, connect your EV3 to your PC with USB cable and then click the green arrow button on the Eclipse toolbar to compile and download the program. The EV3 should restart and the program should run. As a challenge, look at the Unregulated Motor class to see how you can change the program to drive backwards.
 
Note: On first connection of the EV3 with your PC, the EV3 will try install a driver for communication. If that install fails, go to Control Panel, Device Manager, and locate the device in error on the device list. Right click and select update driver and choose the option to check Windows Update for the driver. The correct driver should then be installed.

 

Navigation:

Overview: 
Instructions to build the test robot used for the programming exercises that follow.
Objectives: 

Build the test robot used for the programming exercises that follow.

Content: 

The EV3 programming exercises that follow are based on a simple Lego robot with two motors, a touch sensor, color sensor, gyro sensor and an ultrasonic distance sensor. Attached to this lesson are instructions for building that test robot. There is a project file for Lego Digital Designer that you can load into that tool and follow the build instructions.

There is also a zip file containing the build instructions as html files you view in a browser. Download the file, remove  the _.lxf extension leaving only the .zip extension. You can then unzip the file to a temp directory and click on the file Building Instructions [Stem-Robotics-201-EV3].html to get started.

 

Navigation:

Overview: 
Learn about the example programs provided by leJOS and how to install and use them.
Objectives: 

Download, install and use the example programs provided by leJOS.

Content: 

leJOS provides a set of example programs you can download and install into Eclipse. The examples show how to do a number of things with the leJOS API and are valuable to have available to look at. These examples cover advanced topics and techniques so you should work through the exercises in this unit before looking at these examples.

You can download the examples here. Select the file leJOS_EV3_0.9.1-beta_samples.zip.

The examples are in a zip file. After download, open the zip file and locate the ev3samples directory. Copy or drag and drop this directory into your Eclipse workspace directory. Now, when you open Eclipse, it will include the ev3samples project with the various examples located in the src directory. You can view the examples and run them if you wish.

Navigation:

Overview: 
Create and download your first Java program for the EV3.
Objectives: 

Learn the basics of creating a Java program in Eclipse then downloading it to the EV3 and running it.

Content: 

Now its time to try your first Java program on the EV3. Start Eclipse on your PC. When Eclipse is ready, select New on the File menu. Slide your cursor over and select New Project.

A list of project wizards will appear. Select leJOS EV3 and below that leJOS EV3 Project and click Next. The new project dialog will appear. On this dialog enter a project name of EV3 Exercises. In the JRE box, the first item should be selected and in the drop-down box to the right select JavaSE-1.7. Click Finish.

Your new Java project has been created and should appear in the project explorer on the left side of the Eclipse screen. Click to open the projects items. One will be src, which is the directory where the project source files are stored. Right click on src and select New and then Class. This will display the New Class dialog.

On the New Class dialog, enter HelloWorld for the class name. Check the box to create a static void main method stub. Click Finish. This will create the HelloWorld.java file with the new class in it and open that class file in the editing area. You are ready to program!

Modify the code in the HelloWorld class file to look like this (you can copy and paste the code):

This program will display Hello World!! on the EV3 screen and wait for you to press any button on the EV3 to end the program. Note that we added an import statement to make all of the leJOS hardware classes known to our program. This allows us to use the leJOS Button class without fully qualifying its name. In the Button class we call a method that makes the EV3 stop execution and wait for any button to be pressed.

Now connect your EV3 to your PC with a USB cable. With the leJOS memory card inserted in the EV3, press the center button to turn on the EV3 and start leJOS. Wait until the leJOS menu is displayed on the EV3 screen. Note: On first connection between a PC and the EV3, a device driver will be automatically installed on the PC. Wait until the install completed before proceeding.

When the EV3 menu has appeared, return to Eclipse and click the green run arrow button in the Eclipse menu bar. The Run As dialog will appear to ask how you want to run your program. Select leJOS EV3 Program and click Ok. If you have any unsaved source files, you will be asked if you want to save them. Click Ok. Note that you can and should check the box to have Eclipse always save your files before running your program.

At this point Eclipse will pass your source file through the Java compiler. If errors are found, they will be displayed and the process stops so you can correct the errors. If no errors are found, the program will be downloaded to your EV3 and started. On the EV3 you will see a wait screen displayed (hourglass) and then your program will run. You should see Hello World!! in the top left of the EV3 display. The program will wait at this point until you press any key on the EV3.

Congratulations! You have programmed the EV3 robot controller with Java.

Note in addition to the Java and leJOS documentation available online or as local html files you can open in your browser, if you have questions about a class or method, you can put your cusor on the class instance variable or method name and Eclipse will display documentation for the selected item (if available). If you place your cursor over waitForAnyPress() for example, then the documentation for that method will be displayed.

You can type the name of a class instance followed by a dot and then wait. Eclipse will display the list of public methods and variables for that class. For instance if you typed Button. Eclipse will display a list of all methods and variables available with the Button object along with descriptions for each one. When the window opens you can use your up/down arrows to navigate the list. If you select an item and press Enter, that item will be entered into your code automatically.

A final note, if you look at the package tree in the left pane of Eclipse, you can see that the Hello World class was placed into the default package, since we did not specify a package name in the class.

 

Navigation:

Overview: 
Installation procedure for Eclipse and the leJOS plugin for Eclipse.
Objectives: 

Install the Eclipse IDE and the leJOS plugin for Eclipse.

Content: 
If you do not already have a working Eclipse IDE, you should download Eclipse here. The recommended package of Eclipse is the Eclipse IDE for Java Developers. Install the 32 or 64 bit version matching the bitness of your PC. Eclipse requires Java Run Time (JRE) 8 (1.8) in 32 or 64 bit form matching the bitness of Eclipse. Download here if you do not already have it. 
 
Eclipse is delivered in a .zip file. To install, simply unzip to any directory you wish, though Program Files is a good place. To run Eclipse, double click the executable file. It is best to create a shortcut to the executable file and place the shortcut on your desktop. Eclipse does not modify the Windows registry. To delete Eclipse, simply delete the Eclipse directory.
 
The first time you run Eclipse it will prompt you for a workspace location. It is probably best to go with the default shown in the prompt. The workspace is a directory where your Java projects will be stored.
 
It is best to configure Eclipse to automatically search for updates. On the Eclipse menu bar, click Window -> Preferences. Double click Install/Update in the Preferences list. Highlight Automatic Updates. Check the option to Automatically find new Updates and Notify me. Click Ok. This will keep Eclipse and the leJOS plugin updated.
 
Once Eclipse is installed, you should install the leJOS plugin for Eclipse. Instructions are found here.
 
Here are several resources to help you learn more about Eclipse and how to use it beyond what is covered in our lessons:
 
Video Tutorial
 
Tutorials Point Eclipse Guide
 
Vogella Eclipse Tutorial
 
Official Eclipse Java Tutorial
 

Navigation:

Overview: 
Installation procedure for leJOS and Java.
Objectives: 

Install leJOS and the Java SDK on your PC. Create the SD memory card for the EV3 brick.

Content: 

There are three main steps to installing leJOS. The first two steps are installing the Java and leJOS SDKs on your PC. The third step is creating the leJOS memory card that goes in the EV3. This three part installation process for Windows (Mac users see below) is documented on the leJOS web site here. Open the link and follow the instructions, after reading the following three notes:

Note: Be sure to first install the Java SDK (called JDK) version 7 (1.7) if not already installed on your PC. Install and use version 7 even if you have version 8 or later installed. JDK 7 is now in archive state at oracle. You can download jdk-7u80-windows-i586.exe here. Oracle requires you to create an account to download. When installing, you only need the Development Tools, you can X out Source Code and Public JRE. After this, when you install leJOS with the instructions above, the installer will ask for the location of the JDK you wish to use. Select the folder where JDK 7 was installed. This is typically C:\Program Files (x86 if 64-bit Windows)\Java\jdk1.7.0_80.

Note: The memory card is a micro-SD card and must be between 2GB and 32GB in size and not SDXC. Do not use a smaller or larger size. You may need a micro-SD adapter (sold with most micro-SD cards) to insert the micro-SD into your PC. Be sure you have the card and adapter (if needed) before starting the installation. Read the instructions for running the SD card formatting utility carefully. You will need to download the Java 7 JRE in zipped form per those instructions so it can be transferred to the SD card.

Note: The first time you boot the micro-SD card on an EV3, leJOS will perform an installation process on the card. This will take 10-12 minutes to complete.

After installing leJOS, the documentation for the leJOS EV3 Java API is located at:

C:\Program Files\leJOS EV3\docs\ev3\index.html.

You should open this file in your browser and bookmark it.  You will need this documentation to explore and use the leJOS EV3 classes in your programs.

Installation instructions for Mac are similar and are located here. Note: In step 6.7 of those instructions, you are told to download version 8 of the JRE. However if you look at the picture of the download site, you will see that version 7 is highlighted. Be sure to select version 7.

 

Navigation:

Pages