Download presentation
Presentation is loading. Please wait.
1
Array Lists and the Color Sensor
Lecture 9 Array Lists and the Color Sensor
2
Objectives To learn to use ArrayList objects.
Declaring ArrayLists ArrayList methods Summarize other collection classes. To introduce the EV3 sensors. SensorMode interface SampleProvider interface SensorModes interface Creating color sensor objects Color sensor modes of operation Reading sensor values
3
Array Lists In addition to arrays, which are fixed size, Java also provides several predefined data types called collections. The collection class ArrayList<T> (in the package java.util) creates a list of objects of type T that can dynamically change size. To create an array list of Strings do the following: ArrayList<String> list; Only objects can be stores in an ArrayList (not int, float, char, double, boolean, etc.) Java provides wrapper classes to get around this (Integer, Float, Character, Double, Boolean, etc.) A wrapper class only has one data member and automatically “wraps and unwraps” the data as necessary. Objects of a wrapper class can be generally be used interchangeably with there associated primitive class.
4
Array List Methods ArrayList objects support the following methods.
add – add a new element to the list. list.add(<value>); Also add a new element at a specific index. list.add(<index>,<value>); clear – erase all the elements in the list. list.clear(); contains – return true if and only if the list contains the specified value. list.contains(<value>); get – returns the element at a specified index. list.get(<index>); indexOf – returns the index of the first occurrence of the specified value. list.indexOf(<value>);
5
Array List Methods remove – removes the first occurrence of the specified value or the element at the specified index. Note the index is an int, not an object. list.remove(<value>); list.remove(<index>); size – returns the size of the list. list.size();
6
Array List Demo import java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args){ ArrayList<String> stringList = new ArrayList<String>(); ArrayList<Integer> intList = new ArrayList<Integer>(); stringList.add("World"); stringList.add(0,"Hello"); for (int i = 0; i < stringList.size(); i++) System.out.printf("%s ", stringList.get(i)); System.out.println(); for (int i = 5; i < 20; i++) intList.add(i); for (int i = 0; i < intList.size(); i++) System.out.printf("%d ", intList.get(i));
7
Array List Demo intList.remove(4); //This removes index 4 System.out.println(); for (int i = 0; i < intList.size(); i++) System.out.printf("%d ", intList.get(i)); intList.remove(new Integer(7)); //This removes value 7 System.out.printf("\"World\" is %sin the list%n”, stringList.contains("World") ? "" : "not "); System.out.printf("\"Welcome\" is %sin the list%n", stringList.contains("Welcome") ? "" : "not "); System.out.printf("The index of 14 is %d%n", intList.indexOf(14)); intList.clear(); System.out.printf("intList is %sempty%n", intList.size() == 0 ? "" : "not "); }
8
Other Collection Classes
In addition to the ArrayList class there are several other collection classes. List LinkedList Queue Vector Map SortedMap Set etc. We won’t be covering all of them in this course.
9
EV3 Sensors There are a wide variety of sensors that can be used with an EV3 set. LEGO sensors Third party sensors Vernier Mindsensors.com HiTechnic etc. The general naming convention is leJOS is Manufacturer + Sensor Type + Sensor + Model # Not all the name have all fields. We will be covering the LEGO sensors.
10
LEGO Sensors The EV3 set comes with several sensors and there are a few more that are available. EV3ColorSensor EV3GyroSensor EV3IRSensor EV3TouchSensor EV3UltrasonicSensor These sensors typically have several operating modes and leJOS provides a framework for determining the possible modes and the current mode. These sensors implement an interface called SensorModes. This interface allows us to query the sensor to determine what modes it supports. We can also determine and set the current mode. There is also a SensorMode interface. Objects that satisfy this interface will allow us to collect data from a sensor. We can associate a SensorMode object with a sensor to get its readings.
11
SenorMode Interface The SensorMode interface specifies a single method. getName()– this returns a string description of a mode. A class that implements the SensorMode interface must also implement the SampleProvider interface. A SampleProvider implements two methods. fetchSample(float[] sample, offset) – this fetches a sample from the sensor and stores it in the array starting at the offset position. sampleSize() – this tells the size of a sample for this sensor.
12
SenorMode Interface Why is the sensor interface so complicated?
Some sensors may return more than one value. The number of values returned may depend on the mode the sensor is in. We may want to process the data from the sensor using Adapters and Filters before we use it in our program. There may be new sensors developed and so the interface needs to be as general as possible. In some cases it may be possible to read from a sensor concurrently in more than one mode. The goal is to have a versatile interface that will work in many different circumstances with many different possible outputs.
13
SenorModes Interface The SensorModes interface allows us to communicate with a particular sensor. The return from some of these methods will be a SensorMode object. Modes are specified by passing integer parameters (i.e. mode 0, mode 1, mode 2, etc. ). Modes can also be specified by name (String).
14
SensorModes Inteface The SensorModes interface has the following methods. getAvailableModes() – return an ArrayList of string descriptions for the sensors modes available. getCurrentMode()– gets the index number of the current mode. getMode(int mode) – returns a SensorMode object from which to get information about the specified mode. getMode(String modeName) – returns a SensorMode object from which to get information about the named mode. getModeCount() – returns the number of modes supported by the sensor. setCurrentMode(int mode) – sets the mode to the specified number for fetching samples. setCurrentMode(String modeName) – sets the current mode for fetching samples.
15
Creating Sensor Objects
As with motors we need to create a Java object for each sensor. When we do this we must also specify a port. EV3ColorSensor cs = new EV3ColorSensor(SensorPort.S1); To do this we need to import the following: lejos.hardware.port.* lejos.hardware.sensor.* lejos.robotics.SampleProvider The sensor ports are S1, S2, S3 and S4. As with motors, sensors should be closed when we are done with them. cs.close();
16
SensorModes Example To run the following program you need to plug the color sensor into port 1. import lejos.hardware.*; import lejos.hardware.port.*; import lejos.hardware.sensor.*; import java.util.ArrayList; public class EV3ModesDemo { public static void main(String[] args){ EV3ColorSensor cs = new EV3ColorSensor(SensorPort.S1); ArrayList<String> modes = cs.getAvailableModes(); for (int i = 0; i < modes.size(); i++) System.out.println(modes.get(i)); Button.waitForAnyPress(); cs.close(); }
17
SensorModes Example You should see the following on the EV3 screen.
ColorID Red RGB Ambient The color sensor has 4 modes. ColorID mode measures the color of the surface. The color IDs are specified in a Color class (Color.NONE, Color.BLACK, Color.BLUE, Color.GREEN, Color.YELLOW, Color.RED, Color.WHITE, Color.BROWN) Red mode measures the intensity of reflected red light in the range 0 – 1. RGB mode measures the RGB values of the surface in the range 0 – 1 for each of the three colors. Ambient mode measures the ambient light in the range 0 – 1.
18
Reading the Color Sensor
The following program reads from the color sensor in both ColorID and RGB modes. In ColorID mode the result of each reading is a single floating point number that is can be rounded to an int to produce a Color. In RGB mode the each reading results in three floating point numbers between 0 and 1 representing the intensity of red, green and blue. First we create an object to represent the sensor. EV3ColorSensor cs = new EV3ColorSensor(SensorPort.S1);
19
Reading the Color Sensor
The next step is to create one or more SampleProviders. SampleProvider color = cs.getMode("ColorID"); Now we create an array to store the samples. float[] sampleC = new float[color.sampleSize()]; If you know the sample size you can just use the value. In ColorID, Red, and Ambient modes the sample size is 1. In GRB mode the sample size is 3. If you want to store multiple samples in the array, the size should be an appropriate multiple of the sample size. Finally, you can use the SampleProvider to put sensor values in your array. color.fetchSample(sampleC, 0); The second parameter is the starting index for storing the sample. In our case we are storing a single sample starting at index 0.
20
Color Sensor Demo The following program initializes the color sensor and then read 40 samples. 20 are in ColorID mode. 20 are in RGB mode. Two SampleProviders are created and their use is alternated so the sensor is constantly switching modes. The output in ColorID mode is stored as a float but it is really an int value. We convert it to an int using Math.round(). A method is created to turn this int into a string with the name of the color. The output in RGB mode is three floats. One for red. One for green. One for blue.
21
Color Sensor Demo import lejos.hardware.*; import lejos.hardware.port.*; import lejos.hardware.sensor.*; import lejos.robotics.SampleProvider; import lejos.robotics.Color; import lejos.utility.Delay; public class EV3ColorSensorDemo { static String convertColor(int color){ switch(color){ case Color.NONE: return "None"; case Color.BLACK: return "Black"; case Color.BLUE: return "Blue"; case Color.GREEN: return "Green"; case Color.YELLOW: return "Yellow"; case Color.RED: return "Red"; case Color.WHITE: return "White"; case Color.BROWN: return "Brown"; default: return "Unknown"; }
22
Color Sensor Demo public static void main(String[] args){
EV3ColorSensor cs = new EV3ColorSensor(SensorPort.S1); SampleProvider color = cs.getMode("ColorID"); SampleProvider rgb = cs.getMode("RGB"); float[] sampleC = new float[color.sampleSize()]; float[] sampleRGB = new float[rgb.sampleSize()]; System.out.printf("Color size: %d%n", color.sampleSize()); System.out.printf("GRB size: %d%n", rgb.sampleSize()); for (int i = 0; i < 20; i++){ color.fetchSample(sampleC, 0); rgb.fetchSample(sampleRGB, 0); System.out.println(i + ". " + convertColor(Math.round(sampleC[0]))); System.out.printf("%d. %f %f %f%n", i, sampleRGB[0], sampleRGB[1], sampleRGB[2]); Delay.msDelay(250); } Button.waitForAnyPress(); cs.close();
23
Homework Play with the color sensor and make sure the colors it identifies line up with what you would expect. Investigate the correspondence between the ColorID and the RGB values. Write a paragraph explaining what you find. Modify the program to use the Ambient and Red modes (you may not want to switch rapidly between them). Discuss how these modes are different. Check to see which mode gives the largest contrast between a strip of masking tape and the hall floor outside the classroom.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.