I'm currently programming on a Lego NXT 2.0
with leJOS 0.9.1 beta
firmware.
I have several different sensors, like a color sensor and a ultrasound sensor.
I'm using a while-loop to make the robot drive forward, until it hits a wall. However, for some reason, I don't like this approach and wanted to implement a listener instead. A leJOS developer wrote, however, that using the listener model is not recommended and I should use threads instead to poll the value of the ultrasound sensor.
Now I'm wondering how bad the implementation with a while-loop really is (operating system wise, as in wasting of resources) and how a threading model would be more beneficial (and implemented)?
MWE:
public class SensorTest {
static UltrasonicSensor sonic;
static DifferentialPilot pilot;
public static final int DISTANCE = 20;
public static void main(String[] args){
sonic = new UltrasonicSensor(SensorPort.S1);
pilot = new DifferentialPilot(8.5, 25, Motor.C, Motor.B);
int i = 0;
while (i < DISTANCE) {
pilot.forward();
i = sonic.getDistance();
}
pilot.stop();
}
}