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();
}
}
Not having any experience wit the Lego blocks (I'm serious jealous) you have to ask yourself some serious questions.
In a simple situation, using a loop in this manner may not be a bad solution, but as you add more to, the time it takes to process each request (check n number of sensors, perform n number of operations), it will become slower to react.
A Threaded model may allow you to process more data, but you may need to consider how many threads you need and what they are doing.
For example, you could have a Driver
thread, whose sole responsibility is to move the Lego. It would do this be querying a number of "sensor" thread's to determine what it is telling, but each sensor thread would be polling data at there own rate and not caring about anything else.
You could also inverse the model, allow the Driver
to continue moving until a Sensor
thread raised some kind of alert and told the Driver
it should change directions.
I, personally, would be trying to see if I could get a thread model working (even for a simple device) as it will provide more flexibility into the future to expand the operations...
At the end of the day, it's going to be balancing act
Seriously jealous!