Sensor framework

This is where you talk about the EV3 software itself, installation issues, and programming talk.

Moderators: roger, gloomyandy, skoehler

Re: Sensor framework

Postby ferrer » Sun Aug 10, 2014 4:22 am

wiso wrote:Hi!
I'm trying to learn how to use the sensors. I want to use the EV3Ultrasonicsensor and display on the screen of EV3 the distance to an object at each times. I followed the steps in this post, but I don't know how to show each sample.

Thanks.


Hello wiso,

Here is a sample program to do what you would like:

Code: Select all
import lejos.hardware.Button;
import lejos.hardware.lcd.LCD;
import lejos.hardware.port.SensorPort;
import lejos.hardware.sensor.EV3UltrasonicSensor;

public class UltrasonicDemo {
   public static void main(String[] args) {
      EV3UltrasonicSensor sonar = new EV3UltrasonicSensor(SensorPort.S3);
      float[] samples = new float[sonar.getDistanceMode().sampleSize()];
      while (!Button.ESCAPE.isDown()) {
         sonar.getDistanceMode().fetchSample(samples, 0);
         LCD.drawString(String.format("%3.2f", samples[0]) + " m        ", 0, 3);
      }
      sonar.close();
   }
}


The program begins by creating an EV3UltrasonicSonar object to represent the sonar. Be sure to change the constructor call to correspond to your preferred sensor port; I happened to be using port 3 when writing this.

Next, we create an array to store the data coming in from the sensor. For this sensor, the data is the distance to the object, expressed in meters. We have to use "getDistanceMode()" because this sensor also has a mode for detecting other sensors.

Since the sensor can detect objects from 3 cm to about 250 cm, with a precision of +/- 1 cm, we really only need to see two decimal places. The "String.format" command takes care of that. The spaces I added afterward eliminate any lingering text from a previous reading.

The program ends when the user presses the Escape button (upper left corner of the button panel).
Gabriel J. Ferrer
Hendrix College
ferrer
Novice
 
Posts: 34
Joined: Wed Jan 30, 2008 10:25 pm

Previous

Return to EV3 Software

Who is online

Users browsing this forum: No registered users and 2 guests

more stuff