2

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,

1

You can use the lejos.ev3.robotics.RangeFinder abstraction class:

EV3UltrasonicSensor sensorUS;
RangeFinder sonar;

public UltrasonicSensor(Port port) {
    sensorUS = new EV3UltrasonicSensor(port);
    sonar = new RangeFinder(sensorUS);
}

@Override
public boolean takeControl() {
    return sonar.getRange() < 0.3;
}

Use the float getRange() method to retrieve the distance to the nearest object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.