Array Lists and the Color Sensor

Slides:



Advertisements
Similar presentations
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Advertisements

CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
ARRAYLIST.. Hazen High School. Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Chapter 10 Strings, Searches, Sorts, and Modifications Midterm Review By Ben Razon AP Computer Science Period 3.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
© 2007 Lawrenceville Press Slide 1 Chapter 10 Arrays  Can store many of the same kind of data together  Allows a collection of related values to be stored.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Java SE 8 for Programmers, Third Edition
Computer Science 209 Software Development Java Collections.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Georgia Institute of Technology What is new in Java 5.0 (1.5)? Barb Ericson Georgia Institute of Technology June 2006.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
Quiz: Design a Product Class Create a definition for a class called Product, which keeps track of the following information: –Name of the product –Weight.
Introduction to Robots and the Mind - Programming with Sensors - Bert Wachsmuth & Michael Vigorito Seton Hall University.
CMSC 202 ArrayList Aug 9, 2007.
Using the Java Collection Libraries COMP 103 # T2
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Sixth Lecture ArrayList Abstract Class and Interface
Lecture 6 Arrays and Interfaces.
Lecture 10 Sensors.
Formatting Output & Enumerated Types & Wrapper Classes
(like an array on steroids)
Concepts of Programming Languages
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Software Development Java Collections
COP 3503 FALL 2012 Shayan Javed Lecture 8
A tree set Our SearchTree class is essentially a set.
Computer Programming Methodology Luminance
Continuing Chapter 11 Inheritance and Polymorphism
Week 2: 10/1-10/5 Monday Tuesday Wednesday Thursday Friday
Welcome to CSE 143!.
CMSC 202 Static Methods.
CS 106A, Lecture 19 ArrayLists
TCSS 143, Autumn 2004 Lecture Notes
Programming in Java Lecture 11: ArrayList
Can store many of the same kind of data together
ArrayLists.
Words exercise Write code to read a file and display its words in reverse order. A solution that uses an array: String[] allWords = new String[1000]; int.
A tree set Our SearchTree class is essentially a set.
CMSC 202 ArrayList Aug 9, 2007.
Chapter 10 ArrayList reading: 10.1
Arrays of Objects Fall 2012 CS2302: Programming Principles.
Welcome to CSE 143!.
Can store many of the same kind of data together
Arrays and Collections
Object-Oriented Programming Paradigm
Object Oriented Programming in java
Welcome to CSE 143! Go to pollev.com/cse143.
Barb Ericson Georgia Institute of Technology June 2006
CMSC 202 ArrayList Aug 9, 2007.
slides created by Ethan Apter
Can store many of the same kind of data together
slides created by Marty Stepp
CS 200 Objects and ArrayList
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
slides created by Alyssa Harding
Java Basics Data Types in Java.
Chapter 11 Inheritance and Polymorphism Part 2
Creating and Modifying Text part 3
Review: libraries and packages
Chapter 19 Generics.
Arrays.
Why not just use Arrays? Java ArrayLists.
Presentation transcript:

Array Lists and the Color Sensor Lecture 9 Array Lists and the Color Sensor

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

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.

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>);

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();

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));

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 "); }

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.

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.

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.

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.

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.

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).

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.

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();

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(); }

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.

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);

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.

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.

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"; }

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();

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.