Aegidius
 Plüss   Aplulogo
     
 www.aplu.ch      Print Text 
© 2021, V10.4
 
  NxtLib
 
 

 

Porting Programs from NxtJLib, Event Model

Purpose: Use the EV3 as autonomous rover with a EV3 color sensor. Move the rover on a black floor. Whenever the rover leaves the floor, move it back, so that it remains trapped on the black area forever.

This is exactly the same purpose as in the fifth example of the NxtJLib website. Because the class design of EV3Lib and NxtJLib is the same, the modifications for the source code when porting programs from the NXT to EV3 and vice versa are trivial, despite the completely different hardware and firmware of the two bricks.

Again the Java event model is used here to emphasize the elegance of handling robot behavior by callback methods.

import ch.aplu.ev3.*;

public
 class TrappedRobot implements LightListener
{
  
private final int triggerLevel = 150;
  
private Gear gear;

  
public TrappedRobot()
  
{
    LegoRobot robot 
= new LegoRobot();
    LightSensor ls 
= new LightSensor();
    robot.
addPart(ls);
    ls.
addLightListener(this, triggerLevel);
    gear 
= new Gear();
    gear.
setSpeed(30);
    robot.
addPart(gear);
    gear.
forward();
    Tools.
waitEscape();
    robot.
exit();
  
}

  
public void dark(SensorPort port, int level)
  
{
    gear.
backward(500);
    gear.
left(500);
    gear.
forward();
  
}

  
public void light(SensorPort port, int level)
  
{
  
}

  
public static void main(String[] args)
  
{
    
new TrappedRobot();
  
}
}

Compilation/download using the OnlineEditor of PHBern (Bern University of Teacher Education)

  TrappedRobot

Discussion: Here the new EV3 color sensor is used as light (luminosity) sensor. If you attach the former NXT light sensor, you must use the class NxtLightSensor instead of LightSensor. Because the EV3 color sensor reports light intensity values different from the NXT light sensor, you must adapt the trigger level and even use the dark() callback instead of the bright() callback.

Better you make some preliminary tests by writing out the reported light values with the following short calibration program:

import ch.aplu.ev3.*;
import
 lejos.hardware.lcd.LCD;

public
 class Light1
{
  
public Light1()
  
{
    LegoRobot robot 
= new LegoRobot();
    LightSensor ls 
= new LightSensor(SensorPort.S1);
    robot.
addPart(ls);

    
while (!Tools.isEscapePressed())
    
{  
      
int v = ls.getValue();
      LCD.
drawString("value: " + v, 0, 1);
      LCD.
refresh();
      Tools.
delay(300);
    
}
    robot.
exit();
  
}

  
public static void main(String[] args)
  
{
    
new Light1();
  
}
}
  

Compilation/download using the OnlineEditor of PHBern (Bern University of Teacher Education)