First fare 2010 java-introduction


Published on

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

First fare 2010 java-introduction

  1. 1. Introduction to Javafor FIRST Robotics<br />Andrew MerrillSoftware Mentor, FRC Team 1540Computer Science Teacher, Catlin Gabel School<br />What is Java?<br />Java is a Programming Language<br />documented by the Java Language Specification<br />"Java is object-oriented, strongly typed, with C-like syntax"<br />Java is a Class Library<br />documented by the:<br />Java ME CLDC API Specification, or the<br />Java SE API Specification, or the <br />Java EE API Specification<br />"Java has graphics, threads, networking, data structures, etc..."<br />Java is a Runtime Environment<br />documented by the Java Virtual Machine Specification<br />"Java is compiled to bytecodes which are interpreted by a virtual machine"<br />Goldilocks and the Three Javas<br />Small - Java Micro Edition (ME)<br />designed for mobile and embedded devices<br />used for FRC robotics<br />Medium - Java Standard Edition (SE)<br />designed for regular laptop, desktop, server applications<br />the most common edition<br />widely used in computer science courses (including AP)<br />Large - Java Enterprise Edition (EE)<br />designed for application servers, distributed systems<br />Common Java Misconceptions<br />Java is not limited to Web Programming or Applets<br />Java is not JavaScript, despite the misleadingly similar name!<br />Sample Java Programpublic class DemoBot extends IterativeRobot {  Joystick stick;  Jaguar launcher;    public void teleopInit()  {    stick = new Joystick(1);   // joystick on USB port 1    launcher = new Jaguar(2);  // speed controller on PWM port 2  }    public void teleopPeriodic()  {    if (stick.getTrigger())    // when the joystick trigger is pressed      launcher.set(0.75);      // run launcher at 75% power    else      launcher.set(0.0);       // otherwise, stop the launcher  }}Classes<br />A class defines a new type of object<br />example classes: DemoBot, Joystick, Jaguar<br />Each class contains two kinds of members:<br />Fields: variables that hold data needed by this object<br />example fields: stick, launcher<br />fields are nouns<br />Methods: functions that perform the object's actions<br />example methods: getTrigger, set<br />methods are verbs<br />By convention, class names begin with a capital letter<br />Objects<br />An object is an instance of a class<br />Objects are accessed via variables<br />Variables are declared in advance to refer to objects from a particular class<br />Example:   Jaguar launcher;<br />Objects are created with the operator new<br />Example:     launcher = new Jaguar(2);<br />Members of an object are accessed with the syntax variable.member<br />Example:     launcher.set(0.75);<br />When no variable refers to an object anymore, it is automatically "garbage collected"<br />By convention, variable and function names begin with a lower case letter<br />Inheritance<br />A child class can extend a parent class<br />alternative terminology: a sub-class can extend a super-class<br />Objects of the child class can do everything that objects of the parent class can do<br />child class objects inherit the fields and methods of the parent class<br />allows code to be shared between similar classes<br />Examples:<br />class DemoBot extends IterativeRobot<br />class Jaguar extends PWM<br />class Victor extends PWM<br />class Servo extends PWM<br />Child classes can override parent class methods<br />new method must have the same name and parameters<br />Example: teleopPeriodic() in IterativeRobot <br />Differences from C++<br />no multiple inheritance<br />all methods can be overridden by default<br />all classes extend the built-in Object class<br />Constructors<br />A constructor is a special method in class<br />It is automatically run when a new object is created<br />Constructors always have exactly the same name as the class<br />Constructors have no return type<br />Constructors are often used to initialize the class's fields<br />Example:<br />public class DemoBot extends SimpleRobot {  Joystick stick;  Jaguar launcher;  DemoBot()  {    stick = new Joystick(1);    launcher = new Jaguar(2);  }<br />Interfaces<br />An interface is like a class, but...<br />it has no fields<br />its methods have no bodies<br />So what does it have?<br />method names with their parameters and return type<br />A class can implement an interface (or several interfaces)<br />Think of an interface as a promise to write certain methods<br />Example interface:      interface SpeedController     {          double get();          void set(double speed);     }<br />To implement an interface:<br />class Jaguar extends PWM implements SpeedController<br />Static and Final<br />A static field is a class field, not an object field<br />A final field is a constant - its value can't be changed<br />Example:  static final int maxAngle = 90;<br />Example: Joystick.BUTTON_TRIGGER<br />A static method can be run without making an object first<br />Example:  time = Timer.getUsClock();<br />Packages and Importing<br />Java classes can be organized into packages<br />Each package goes in a separate directory (or folder)<br />How to use a class from the package edu.wpi.first.wpilibj:<br />Write the package name every time you use the class name<br />Example:   stick = new edu.wpi.first.wpilibj.Joystick(1);<br />or import the class from the package<br />Example:   import edu.wpi.first.wpilibj.Joystick;<br />or import every class from the package<br />Example:   import edu.wpi.first.wpilibj.*;<br />The Java library package java.lang is always imported automatically<br />Class Member Access Control<br />Java restricts who can access the members of a class<br />Can be accessed from the same classCan be accessed from the same packageCan be accessed from any child classCan be accessed from any classprivateyesnonono(default)yesyesnonoprotectedyesyesyesnopublicyesyesyesyes<br />Java Data Types<br />Number Types<br />Integers<br />byte (8 bits, range from -128 to 127)<br />short (16 bits, range of _ 32767)<br />int (32 bits, range of about _ 2 billion)<br />long (64 bits, range of about _ 9 quintillion or 1019)<br />Floating Point<br />float (32 bits, range of about _ 1038, precision of about 7 decimal digits)<br />double (64 bits, range of about _ 10308, precision of about 16 decimal digits)<br />Other Types<br />boolean (true or false)<br />char (one Unicode character)<br />String (standard library class)<br />wrapper classes: Byte, Short, Integer, Long, Float, Double, Boolean, Character<br />Note: No unsigned numbers, unlike C/C++ Math<br />+ for addition<br />- for subtraction<br />* for multiplication<br />/ for division (warning: if you divide two integer types, you'll get an integer type result)<br />% for remainder after division (for example, 10 % 3 is 2)<br />Math.sqrt(x) for square root<br />Math.abs(x) for absolute value<br />Math.min(a,b), Math.max(a,b) for minimum and maximum<br />Math.sin(x), Math.cos(x), Math.tan(x) for trigonometry<br />If you need more math functions: import com.sun.squawk.util.MathUtils<br />MathUtils.pow(a,b), MathUtils.log(a), MathUtils.atan2(y,x)<br />Randomness<br />The Java library provides a class called Random<br />It is in the java.util package, so you should import java.util.Random;<br />A Random object is a random number generator<br />Only create one random number generator per program!<br />Example: public static Random generator = new Random();<br />Example: How to generate a random integer in the range 0...359:<br />int spinDirection = generator.nextInt(360);<br />Example: How to generate a random floating point number in the range 0...1:<br />double probability = generator.nextDouble();<br />Casting<br />To force a double into an int (losing the decimal part):<br />int x = (int) 3.7;<br />To force an int to be treated as a double:<br />double average = ((double) total) / count;<br />To tell Java that an Object is really a Jaguar:<br />Jaguar launcher = (Jaguar) getSpeedController();<br />Exceptions<br />When your program crashes, Java throws an Exception<br />Example:<br />java.lang.ArithmeticException: / by zero   at DemoBot.teleopPeriodic(<br />You can catch and handle Exceptions yourself:<br />try {     // do possibly dangerous stuff here     // keep doing stuff} catch (Exception e) {    launcher.set(0);    System.out.println("launcher disabled");    System.out.println("caught: " + e.getMessage());}<br />Java ME Data Structures<br />Arrays<br />Fixed number of elements<br />All elements of the same type (or compatible types)<br />Random access by element index number<br />Useful array utilities in the package com.sun.squawk.util.Arrays<br />sort, copy, fill, binarySearch<br />Example:<br />int data[] = new int[100];data[0] = 17;data[5] = data[0] + 1;System.out.println(data[17]);<br />Vector<br />Variable number of elements<br />All elements must be objects<br />Random access by element index number<br />import java.util.Vector;<br />Example:<br />Vector speedControllers = new Vector();speedControllers.addElement(new Jaguar(1));Jaguar controller = (Jaguar) speedControllers.elementAt(0);<br />Hashtable<br />Otherwise known as a dictionary, map, associative array, lookup table<br />Given a key, can quickly find the associated value<br />Both the key and value must be objects<br />import java.util.Hashtable;<br />Example:<br />Hashtable animals = new Hashtable();animals.put("cow", "moo");animals.put("chicken", "cluck");animals.put("pig", "oink");String chickenSound = (String) animals.get("chicken");System.out.println("a chicken goes" + chickenSound);<br />Other Data Structures:<br />SortedVector in edu.wpi.first.wpilibj.util<br />Stack in java.util<br />IntHashtable in com.sun.squawk.util<br />Resources<br />Websites<br />WPI's Java for FRC page:<br /><br />Read Getting Started With Java For FRC and WPI Library Users Guide<br />Download the JavaDoc class library reference for WPILibJ<br />FRC 2011 Java Beta Test Forum:<br /><br />Java Forum on Chief Delphi<br /><br />Official Sun/Oracle Java Tutorial<br /><br />Books<br />Java in a Nutshell by David Flanagan (O'Reilly)<br />Effective Java by Joshua Bloch<br />Using Java for FRC RoboticsInstalling Java for FRC<br />You do not need LabView or WindRiver Workbench (C++) installed<br />In fact, you don't need anything from the FIRST DVD<br />Works on Windows (including Windows 7), Mac OS X, and Linux<br />Download the Java SE JDK and the NetBeans IDE<br />The Java SE JDK is available from<br />NetBeans is available from (get the Java SE version)<br />OR, you can download the Java JDK/NetBeans Bundle from Sun/Oracle<br />Install the JDK and NetBeans<br />Follow the instructions in Getting Started With Java for FRC to download and install FRC plugins:<br />Select Tools -> Plugins -> Settings, and click Add<br />Type the Name "FRC Java"<br />Type the URL ""<br />On the Available Plugins tab, select the 5 FRC Java plugins, and click Install<br />Accept all of the agreements, and ignore the validation warning<br />Restart NetBeans<br />Select Tools -> Options (or NetBeans -> Preferences on a Mac)<br />Select Miscellaneous -> FRC Configuration and enter your team number<br />You're done!<br />After installing the plugins, you should have a sunspotfrcsdk folder in your home directory<br />sunspotfrcsdk/doc/javadoc/index.html has the class library documentation<br />sunspotfrcsdk/lib/WPILibJ/src has the class library source code<br />Creating and Running a Java Program<br />From the File menu, select New Project<br />Select the "FRC Java" category<br />Select a template:<br />IterativeRobotTemplateProject or SimpleRobotTemplateProject<br />Click Next<br />Give your project a Project Name<br />Change the Project Location if you want<br />Click Finish<br />To run your program, either:<br />Select Run Main Project from the Run menu; or<br />Click the green triangle in the toolbar; or<br />Press F6<br />Whichever means you choose, this will:<br />Compile and build your project<br />Download your program to the cRio<br />Reboot the cRio to run your program<br />Wait for it to say it is waiting for the cRio to reboot<br />Then move to the Driver Station<br />Wait for the "Communication" and "Robot Code" lights to go from red to green<br />Click "Enable" to start the program<br />SimpleRobot vs. IterativeRobot<br />Your robot class will extend either SimpleRobot or IterativeRobot<br />The SimpleRobot class provides two methods you should override:<br />autonomous(), which is called when autonomous mode starts<br />operatorControl(), which is called when teleoperated mode starts<br />You need to write your own loops in these functions to keep them running<br />You can execute a sequence of actions easily<br />make sure to run getWatchdog().feed() inside your loop<br />The IterativeRobot classes provides more methods to overide:<br />disabledInit(), autonomousInit(), teleopInit()<br />called when the robot enters the given mode<br />disabledPeriodic(), autonomousPeriodic(), teleopPeriodic()<br />called approx. every 10 ms<br />disabledContinuous(), autonomousContinuous(), teleopContinuous()<br />called as fast as the robot can<br />The IterativeRobot provides the main loop for you, and calls the appropriate functions<br />You need to design your own state machine to execute a sequence of actions<br />Displaying Diagnostic Output<br />Option 1: System.out.println()<br />This is the usual way to display text output from a Java program<br />Example: System.out.println("current speed is " + speed);<br />To view the output, install the NetConsole viewer<br />NetConsole requires the National Instruments LabView libraries (installed from the FIRST DVD)<br />Download NetConsole from<br />More info is at (Team Update 4.0)<br />Option 2: Driver Station User Messages<br />There is a six line area for User Messages on the Driver Station<br />You can display text in it using the DriverStationLCD class<br />Example (displays "Shoot the Ball!" on line 2, column 1):<br />   DriverStationLCD dsLCD = DriverStationLCD.getInstance();   dsLCD.println(DriverStationLCD.Line.kUser2, 1, "Shoot the Ball!");   dsLCD.updateLCD();<br />Option 3: SmartDashboard<br />This is a new class for 2011, currently only in beta<br />More info in the next portion of the presentation<br />