I'm using ev3 ultrasonic sensor. And I'm writing a behavior based lejos code. I want to do some tasks when the ultrasonic sensor detects an object which is not further than 30 cm's. And this is my code:
public UltrasonicSensor(Port port)
{
sonar = new EV3UltrasonicSensor(port);
sonar.getDistanceMode().fetchSample(value, 0);
}
@Override
public boolean takeControl() {
// TODO Auto-generated method stub
return value[0] < 0.3;
public void action() {
....
}
@Override
public void suppress() {
// TODO Auto-generated method stub
suppressed = true;
}
But I think it is not the right way. How can I implement it in the right way?
Thanks for help,
It appears you are only fetching a distance sample from the ultrasonic sensor once. Get a SampleProvider
object from the getDistanceMode()
, store it in a global variable, and call fetchSample()
on it each time you want a new sample.
However, you may want to make sure that you don't ask the sensor for a new sample too often, as this may overload it with ping requests. Sound can be slow in comparison to how fast your program runs.