leJOS API
Buttons
The EV3 buttons are accessed by integer fields:
- Button.ID_ENTER
- Button.ID_ESCAPE
- Button.ID_LEFT
- Button.ID_RIGHT
To test if a button is pressed, you use:
/*
* Example on how to check the buttons pressed
*/
import lejos.hardware.Button;
import lejos.hardware.Sound;
import lejos.utility.Delay;
public class ButtonsTest {
public static void main(String[] args)
{
int pressed;
//print the button name untill the pressed button is escape
while(Button.getButtons()!=Button.ID_ESCAPE)
{
// block the thread until a button is pressed
Button.waitForAnyPress();
pressed = Button.getButtons();
//left button
if(pressed == Button.ID_LEFT){
System.out.println("Left");
}
//right button
if(pressed == Button.ID_RIGHT){
System.out.println("Right");
}
//up button
if(pressed == Button.ID_UP){
System.out.println("Up");
}
//down button
if(pressed == Button.ID_DOWN){
System.out.println("Down");
}
//enter button
if(pressed == Button.ID_ENTER){
System.out.println("Enter");
}
//escape button
if(pressed == Button.ID_ESCAPE){
System.out.println("Escape");
}
}
}
}
Controlling the Sensors
The EV3 comes with four sensors: the touch sensor, the light sensor, the infrared sensor, and the ultrasonic sensor. The port for each sensor is either SensorPort.S1, SensorPort.S2, SensorPort.S3 or SensorPort.S4. In your code, the sensor classes must indicate which port they are plugged into. This can be done by using the Port class
lejos.hardware.port.SensorPort
.
Touch Sensor
The touch sensor is the most basic sensor in the EV3 robotics kit. It has a simple switch activated by a red button on the front. To use a touch sensor, you create an instance of it attached to a sensor port, using the constructor
EV3TouchSensor touchSensor = new EV3TouchSensor(SensorPort.S1);
/*
* Example on how to check if the touch sensor is pressed
*/
import lejos.hardware.sensor.EV3TouchSensor;
import lejos.hardware.sensor.SensorMode;
import lejos.hardware.Button;
import lejos.hardware.port.SensorPort;
public class TouchTest {
static EV3TouchSensor touchSensor = new EV3TouchSensor(SensorPort.S1);
public static void main(String[] args) throws InterruptedException {
// block the thread until a button is pressed
Button.waitForAnyPress();
/*get an instance of this sensor in measurement mode to
detect when the sensor is pressed */
SensorMode toucher = touchSensor.getTouchMode();
// initialize an array of floats for fetching samples
float [] samplevalue = new float [toucher.sampleSize()];
while(Button.getButtons() != Button.ID_ESCAPE)
{
// fetch a sample: the value is stored at location 0 in the samplevalue: samplevalue[0]
toucher.fetchSample(samplevalue, 0);
//print on the screen the state of the touch sensor
System.out.println("value"+ samplevalue[0]);
Thread.sleep(100);
}
}
}
Light and Color Sensor
To use a light/color sensor, you create an instance of it attached to a sensor port, using the constructor
public EV3ColorSensor(SensorPort port);
/*
* Example on how to test the color sensor
*/
import lejos.hardware.sensor.EV3ColorSensor;
import lejos.hardware.Button;
import lejos.hardware.port.SensorPort;
public class colorTest {
static EV3ColorSensor colorSensor = new EV3ColorSensor(SensorPort.S2);
public static void main(String[] args)
{
// block the thread until a button is pressed
Button.waitForAnyPress();
int color_value = colorSensor.getColorID();
while(Button.getButtons() != Button.ID_ESCAPE)
{
color_value = colorSensor.getColorID();
if(color_value==0){
System.out.println("None");
}
if(color_value==1){
System.out.println("Black");
}
if(color_value==2){
System.out.println("Blue");
}
if(color_value==3){
System.out.println("Green");
}
if(color_value==4){
System.out.println("Yellow");
}
if(color_value==5){
System.out.println("Red");
}
if(color_value==6){
System.out.println("White");
}
if(color_value==7){
System.out.println("Brown");
}
}
}
}
Infrared Sensor
The IR detects the distance of an object in front of it.
/*
* Example on how to get distances from the IR sensor
*/
import lejos.hardware.sensor.EV3IRSensor;
import lejos.hardware.sensor.SensorMode;
import lejos.hardware.Button;
import lejos.hardware.port.SensorPort;
public class irTest {
static EV3IRSensor irSensor = new EV3IRSensor(SensorPort.S1);
public static void main(String[] args) throws InterruptedException
{
// block the thread until a button is pressed
Button.waitForAnyPress();
// get an instance of this sensor in measurement mode
SensorMode irDistance = irSensor.getDistanceMode();
// initialize an array of floats for fetching samples
float [] samplevalue = new float [irDistance.sampleSize()];
while(Button.getButtons() != Button.ID_ESCAPE)
{
// fetch a sample store it at location 0 in the samplevalue array: samplevalue[0]
irDistance.fetchSample(samplevalue, 0);
//print on the screen the value of the distance detected by IR
System.out.println("value"+ samplevalue[0]);
Thread.sleep(100);
}
}
}
Controlling the Motors
Motors are the source of all movement in the Lego EV3 kit. They are connected dirrectly to the EV3 brick via the A, B, C and D ports.
To work with the three motors provided in the Lego EV3 kit, you have to import the lejos.hardware.motor package. Motor ports can be accessed using static variables:
The most basic methods for controlling motors are:
void setSpeed(int speed)
void forward()
Motor turns until commanded to stop; program continues execution
void backward()
void stop()
Stops the motor immediately.
void flt()
Puts the motor in float mode and it will glide to a stop (don't apply the break)
You can determine how well this is working by getting the actual speed of the motor
int getActualSpeed()
If you do not want speed regulation, you can call
void regulateSpeed(boolean yes)
and switch regulation off. When motors are not being regulated, you may wish to set the
power directly, rather than to set the speed. To do this you can call
synchronized void setPower(int power)
The direction of the motor can be changed with
void reverseDirection()
The built-in tachometer in the EV3 motor can be reset by
void resetTachoCount()
and read by
int getTachoCount()
The tachometer can be used to rotate a motor by an angle, in degrees. The angle can be negative.
void rotate(int angle);
or
void rotate(int angle, boolean immediateReturn)
An absolute rather than relative angle can also be specified
void rotateTo(int limitAngle)
or
void rotateTo(int limitAngle,boolean immediateReturn)
You can test if a motor is moving by
boolean isMoving()
This is useful to test if the motor has finished rotating. isMoving()returns true when the motor is moving for any reason (e.g. forward() or backward() have been called), and not only if a rotate operation is in place.
To specifically test to see if a rotate operation is currently in progress, call
public boolean isRotating()
The angle that you are currently rotating to can be determined by calling
int getLimitAngle()
The regulation thread also implements smooth acceleration to prevent jerking motion
when speed is increased or decreased. This can be switched on and off, by
void smoothAcceleration(boolean yes)
There are set of methods for getting information about the current state of the motor:
int getSpeed()
int getMode()
int getPower()
boolean isRegulating()
boolean isForward()
boolean isBackward()
boolean isFloating()
As well as controlling speed regulation and smooth acceleration, the regulation thread also controls rotation and bringing the motors to a smooth stop at the limit angle. If a motor is being used in a very simple way that does not require any of these regulation functions, you can shut down the regulation thread by calling
void shutdown()
Controlling Wheeled Vehicles
One of the most common form of robots created using the Mindstorms EV3 are wheeled vehicles, and leJOS contains several classes that specifically support wheeled vehicles.
The MovePilot class is used to control vehicles with two independently driven wheels, that can turn on the spot.
It steers such a vehicle using two regulated motors. A pilot does not keep track on the
position or bearing of a robot, that is the job of a Navigator.
The Pilot constructor needs to know the diameter of the wheels of the vehicle and the
width of the track, i.e. the distance between the centers of the tracks of the two wheels.
These measurements can be in any units as it is the ratio between them that is important,
not the measurement units.
The DifferentialPilot class has more precise methods. It's constructor also needs to know what Motors are used, and whether driving them
forwards drives the robot forward or backward.
The constructor looks like
public DifferentialPilot(float wheelDiameter,float trackWidth,Motor leftMotor, Motor rightMotor)
Otherwise, use the following constructor to set the Boolean variable reverse to true so that the motors will then rotate backward to make the robot move forward:
public DifferentialPilot(float wheelDiameter,float trackWidth,Motor leftMotor, Motor rightMotor, boolean reverse)
The main methods of a pilot are:
void setTravelSpeed(double travelSpeed)
motors in the same unit of distance (if diameter of the wheel is measured in centimeters, then the number set by this method will be in centimeters per second)
void setRotateSpeed(value)
Speed in degrees per second
void setAcceleration(int)
Determines how quickly robot achieves maximum speed. If acceleration is too high, start of move may be erratic
void forward()
Moves the robot forward until it is stopped or another movement method is called
void backward()
Moves the robot backwards
void stop()
Stops the robot
void rotate(int angle)
Rotates the robot on its axis by the number of degrees specified. negative int = opposite direction to positive
void rotate(int angle, boolean immediateReturn)
Rotates the robot on its axis by the number of degrees specified. If you want the thread to do other things while the robot is rotating, use the second variant of the method and set immediateReturn = true.
boolean isMoving()
void travel(double distance)
Moves the motors a specified distance in the same unit as the wheel diameter; negative = backwards
void travel(double distance,boolean immediateReturn)
Goes to next command after starting motors. Robot will stop when it has traveled specified distance OR a succeeding command changes the motion forward and backward commands are the same as travel(value, true) except the movement only changes when another command is sent to the pilot
getMovement().getDistanceTraveled()
Returns the distance the vehicle traveled
void steer(int turnRate)
Turns with one wheel stationary. positive: left wheel is stationary; negative: right wheel is stationary
void steer(int turnRate, int angle)
void steer(int turnRate, int angle, boolean immediateReturn)
Makes a curved turn rather than rotating in place. if value1= 90 (or -90), inside wheel does not turn. if value1 < 90, inside wheel moves forward, but less than outside wheel if value1 > 90, inside wheel turns backward. steer(180, value2)=rotate(value2) value2 determines how many degrees of a circle the robot travels
/*
* Example on how to drive a EV3 wheeled robot forward using lejos
*/
import lejos.robotics.navigation.*;
import lejos.hardware.motor.EV3LargeRegulatedMotor;
import lejos.hardware.port.MotorPort;
import lejos.robotics.chassis.Chassis;
import lejos.robotics.chassis.Wheel;
import lejos.robotics.chassis.WheeledChassis;
import lejos.hardware.Button;
public class MovePilotExample {
static EV3LargeRegulatedMotor LEFT_MOTOR = new EV3LargeRegulatedMotor(MotorPort.A);
static EV3LargeRegulatedMotor RIGHT_MOTOR = new EV3LargeRegulatedMotor(MotorPort.C);
public static void main(String[] args) throws Exception{
// Don't start until a button is pressed
Button.waitForAnyPress();
/* setup the wheel diameter of left (and right) motor in centimeters (2.0 cm)
the offset number is the distance between the center of wheel
to the center of robot (half of track width)*/
Wheel wheel1 = WheeledChassis.modelWheel(LEFT_MOTOR , 2.0).offset(-7.5);
Wheel wheel2 = WheeledChassis.modelWheel(RIGHT_MOTOR , 2.0).offset(7.5);
// set up the chassis type: Differential pilot
Chassis chassis = new WheeledChassis(new Wheel[] { wheel1, wheel2 }, WheeledChassis.TYPE_DIFFERENTIAL);
MovePilot pilot = new MovePilot(chassis);
//drive the robot forward infinitly or untill commanded to stop
pilot.forward();
//if you want the robot to travel a certain distance (100 cm in this case)
//negative distance moves the robot in the oposite dirrection
//pilot.travel(100);
//if you want to turn 90 degrees
//pilot.rotate(90);
// press the ESCAPE button to stop moving
while (pilot.isMoving()) {
if(Button.getButtons()==Button.ID_ESCAPE) {
//stop the movement of the robot
pilot.stop();
}
// block the thread until a button is pressed
Button.waitForAnyPress();
}
}
}
How To Add a Pause in Your Program
try {
// amountOfTime in miliseconds
Thread.sleep(amountOfTime);
}
catch(Exception e) {
}