I am currently working with the LeJOS Ev3 library and have programmed the following listener:
import lejos.hardware.port.Port;
import robots.ev3.drive.parts.LightSensor;
public abstract class LightListener {
protected int trigger;
protected boolean dark;
public LightListener(int triggerLevel) { trigger = triggerLevel; }
public void notify(LightSensor s) {
// Depending on the value that s measures, either the method
// dark or bright is called
}
public void initialValue(int level) {
dark = level < trigger;
}
abstract public void bright(Port port, int level);
abstract public void dark(Port port, int level);
}
As you can see, there is a method called notify that is supposed to call different methods, depending on what the sensor is measuring. I would like to be able to call the method notify only when the value the sensor is measuring changes, without using a while-loop that constantly checks if the value has changed. But I couldn't think of or find the way to achieve this.
The only thing that occurred to me, is to start a thread that would run this code:
while(true) {
waitForSensorValueToChange();
listener.notify(sensor);
}
But, again, I don't even know if it is possible to wait for an event to happen (without constantly checking the values).
EDIT - Since it has been repeatedly been suggested to me, I will mention that I already added a method on my LightSensor called addLightListener(LightListener listener). This does not solve my problem with avoiding to poll.