25
Introduction to Java for FIRST Robotics Andrew Merrill Software Mentor, FRC Team 1540 Computer Science Teacher, Catlin Gabel School What is Java? Java is a Programming Language o documented by the Java Language Specification

First fare 2010 java-introduction

Embed Size (px)

Citation preview

Page 1: First fare 2010 java-introduction

Introduction to Javafor FIRST Robotics

Andrew MerrillSoftware Mentor, FRC Team

1540Computer Science Teacher,

Catlin Gabel School

What is Java? Java is a Programming Language

o documented by the Java Language Specification

o "Java is object-oriented, strongly typed, with C-like syntax"

Java is a Class Libraryo documented by the:

Java ME CLDC API Specification , or the Java SE API Specification , or the Java EE API Specification

o "Java has graphics, threads, networking, data structures, etc..."

Page 2: First fare 2010 java-introduction

Java is a Runtime Environmento documented by the Java Virtual Machine

Specificationo "Java is compiled to bytecodes which are

interpreted by a virtual machine"

Goldilocks and the Three Javas Small - Java Micro Edition (ME)

o designed for mobile and embedded deviceso used for FRC robotics

Medium - Java Standard Edition (SE)o designed for regular laptop, desktop, server

applicationso the most common editiono widely used in computer science courses

(including AP) Large - Java Enterprise Edition (EE)

o designed for application servers, distributed systems

Common Java Misconceptions Java is not limited to Web Programming or Applets Java is not JavaScript, despite the misleadingly similar

name!

Sample Java Program

public class DemoBot extends IterativeRobot {  Joystick stick;

Page 3: First fare 2010 java-introduction

  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 A class defines a new type of object

o example classes: DemoBot, Joystick, Jaguar

Each class contains two kinds of members:o Fields: variables that hold data needed by this

object example fields: stick, launcher fields are nouns

o Methods: functions that perform the object's actions

Page 4: First fare 2010 java-introduction

example methods: getTrigger, set methods are verbs

By convention, class names begin with a capital letter

Objects An object is an instance of a class Objects are accessed via variables Variables are declared in advance to refer to objects

from a particular classo Example:   Jaguar launcher;

Objects are created with the operator newo Example:     launcher = new Jaguar(2);

Members of an object are accessed with the syntax variable.member

o Example:     launcher.set(0.75); When no variable refers to an object anymore, it is

automatically "garbage collected" By convention, variable and function names begin

with a lower case letter

Inheritance A child class can extend a parent class

o alternative terminology: a sub-class can extend a super-class

Objects of the child class can do everything that objects of the parent class can do

Page 5: First fare 2010 java-introduction

o child class objects inherit the fields and methods of the parent class

o allows code to be shared between similar classes Examples:

o class DemoBot extends IterativeRobot

o class Jaguar extends PWMo class Victor extends PWMo class Servo extends PWM

Child classes can override parent class methodso new method must have the same name and

parameterso Example: teleopPeriodic()

in IterativeRobot Differences from C++

o no multiple inheritanceo all methods can be overridden by defaulto all classes extend the built-in Object class

Constructors A constructor is a special method in class It is automatically run when a new object is created Constructors always have exactly the same name as

the class Constructors have no return type Constructors are often used to initialize the class's

fields Example:

public class DemoBot extends SimpleRobot {  Joystick stick;

Page 6: First fare 2010 java-introduction

  Jaguar launcher;

  DemoBot()  {    stick = new Joystick(1);    launcher = new Jaguar(2);  }

Interfaces An interface is like a class, but...

o it has no fieldso its methods have no bodies

So what does it have?o method names with their parameters and return

type A class can implement an interface (or several

interfaces) Think of an interface as a promise to write certain

methods Example interface:

      interface SpeedController     {          double get();          void set(double speed);     }

To implement an interface:o class Jaguar extends PWM implements SpeedController

Static and Final

Page 7: First fare 2010 java-introduction

A static field is a class field, not an object field A final field is a constant - its value can't be changed Example:  static final int maxAngle = 90;

Example: Joystick.BUTTON_TRIGGER A static method can be run without making an object

first Example:  time = Timer.getUsClock();

Packages and Importing Java classes can be organized into packages Each package goes in a separate directory (or folder) How to use a class from the package edu.wpi.first.wpilibj:

o Write the package name every time you use the class name

Example:   stick = new edu.wpi.first.wpilibj.Joystick(1);

o or import the class from the package Example:   import edu.wpi.first.wpilibj.Joystick;

o or import every class from the package Example:   import edu.wpi.first.wpilibj.*;

The Java library package java.lang is always imported automatically

Page 8: First fare 2010 java-introduction

Class Member Access Control

Java restricts who can access the members of a class

Can be accessed from the

same class

Can be accessed from the

same package

Can be accessed

from any child

class

Can be accessed

from any class

private yes no no no

(default) yes yes no noprotected yes yes yes nopublic yes yes yes yes

Java Data Types Number Types

o Integers byte (8 bits, range from -128 to 127) short (16 bits, range of _ 32767) int (32 bits, range of about _ 2 billion) long (64 bits, range of about _ 9 quintillion

or 1019)o Floating Point

float (32 bits, range of about _ 1038, precision of about 7 decimal digits)

Page 9: First fare 2010 java-introduction

double (64 bits, range of about _ 10308, precision of about 16 decimal digits)

Other Typeso boolean (true or false)o char (one Unicode character)

String (standard library class) wrapper classes: Byte, Short, Integer, Long, Float, Double, Boolean, Character

Note: No unsigned numbers, unlike C/C++

Math + for addition - for subtraction * for multiplication / for division (warning: if you divide two integer

types, you'll get an integer type result) % for remainder after division (for example, 10 % 3 is

2) Math.sqrt(x) for square root Math.abs(x) for absolute value Math.min(a,b), Math.max(a,b) for

minimum and maximum Math.sin(x), Math.cos(x), Math.tan(x) for trigonometry

If you need more math functions: import com.sun.squawk.util.MathUtils

o MathUtils.pow(a,b), MathUtils.log(a), MathUtils.atan2(y,x)

Page 10: First fare 2010 java-introduction

Randomness The Java library provides a class called Random It is in the java.util package, so you should import java.util.Random;

A Random object is a random number generator Only create one random number generator per

program!o Example: public static Random generator = new Random();

Example: How to generate a random integer in the range 0...359:

o int spinDirection = generator.nextInt(360);

Example: How to generate a random floating point number in the range 0...1:

o double probability = generator.nextDouble();

Casting To force a double into an int (losing the decimal

part):o int x = (int) 3.7;

To force an int to be treated as a double:o double average = ((double) total) / count;

To tell Java that an Object is really a Jaguar:

Page 11: First fare 2010 java-introduction

o Jaguar launcher = (Jaguar) getSpeedController();

Exceptions When your program crashes, Java throws an

Exception Example:

java.lang.ArithmeticException: / by zero   at DemoBot.teleopPeriodic(DemoBot.java:15)

You can catch and handle Exceptions yourself: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());}

Java ME Data Structures Arrays

o Fixed number of elementso All elements of the same type (or compatible

types)

Page 12: First fare 2010 java-introduction

o Random access by element index numbero Useful array utilities in the

package com.sun.squawk.util.Arrays sort, copy, fill, binarySearch

o Example:int data[] = new int[100];data[0] = 17;data[5] = data[0] + 1;System.out.println(data[17]);

Vectoro Variable number of elementso All elements must be objectso Random access by element index numbero import java.util.Vector;o Example:

Vector speedControllers = new Vector();speedControllers.addElement(new Jaguar(1));Jaguar controller = (Jaguar) speedControllers.elementAt(0);

Hashtableo Otherwise known as a dictionary, map,

associative array, lookup tableo Given a key, can quickly find the associated

valueo Both the key and value must be objectso import java.util.Hashtable;o Example:

Hashtable animals = new Hashtable();animals.put("cow", "moo");

Page 13: First fare 2010 java-introduction

animals.put("chicken", "cluck");animals.put("pig", "oink");String chickenSound = (String) animals.get("chicken");System.out.println("a chicken goes" + chickenSound);

Other Data Structures:o SortedVector in edu.wpi.first.wpilibj.util

o Stack in java.utilo IntHashtable in com.sun.squawk.util

Resources Websites

o WPI's Java for FRC page: http://first.wpi.edu/FRC/frcjava.html

Read Getting Started With Java For FRC and WPI Library Users Guide

Download the JavaDoc class library reference for WPILibJ

o FRC 2011 Java Beta Test Forum: http://forums.usfirst.org/forumdisplay.php?

f=1462o Java Forum on Chief Delphi

http://www.chiefdelphi.com/forums/ forumdisplay.php?f=184

o Official Sun/Oracle Java Tutorial http://download.oracle.com/javase/tutorial/

Bookso Java in a Nutshell by David Flanagan (O'Reilly)

Page 14: First fare 2010 java-introduction

o Effective Java by Joshua Bloch

Using Java for FRC Robotics

Installing Java for FRC You do not need LabView or WindRiver Workbench

(C++) installed In fact, you don't need anything from the FIRST DVD Works on Windows (including Windows 7), Mac OS

X, and Linux1. Download the Java SE JDK and the NetBeans IDE

o The Java SE JDK is available from http://java.sun.com

o NetBeans is available from http://netbeans.org/downloads (get the Java SE version)

o OR, you can download the Java JDK/NetBeans Bundle from Sun/Oracle

2. Install the JDK and NetBeans3. Follow the instructions in Getting Started With Java

for FRC to download and install FRC plugins:A. Select Tools -> Plugins -> Settings,

and click AddB. Type the Name "FRC Java"C. Type the URL

"http://first.wpi.edu/FRC/java/netbeans/update/updates.xml"

Page 15: First fare 2010 java-introduction

D. On the Available Plugins tab, select the 5 FRC Java plugins, and click Install

E. Accept all of the agreements, and ignore the validation warning

F. Restart NetBeansG. Select Tools -> Options (or NetBeans -> Preferences on a Mac)

H. Select Miscellaneous -> FRC Configuration and enter your team number

4. You're done! After installing the plugins, you should have

a sunspotfrcsdk folder in your home directoryo sunspotfrcsdk/doc/javadoc/index.html has the class library documentation

o sunspotfrcsdk/lib/WPILibJ/src has the class library source code

Creating and Running a Java Program From the File menu, select New Project Select the "FRC Java" category Select a template:

o IterativeRobotTemplateProject or SimpleRobotTemplateProject

Click Next Give your project a Project Name Change the Project Location if you want Click Finish To run your program, either:

Page 16: First fare 2010 java-introduction

o Select Run Main Project from the Run menu; or

o Click the green triangle in the toolbar; oro Press F6

Whichever means you choose, this will:o Compile and build your projecto Download your program to the cRioo Reboot the cRio to run your program

Wait for it to say it is waiting for the cRio to reboot Then move to the Driver Station Wait for the "Communication" and "Robot Code"

lights to go from red to green Click "Enable" to start the program

SimpleRobot vs. IterativeRobot Your robot class will extend either SimpleRobot

or IterativeRobot The SimpleRobot class provides two methods you

should override:o autonomous(), which is called when

autonomous mode startso operatorControl(), which is called when

teleoperated mode startso You need to write your own loops in these

functions to keep them runningo You can execute a sequence of actions easilyo make sure to run getWatchdog().feed()

inside your loop

Page 17: First fare 2010 java-introduction

The IterativeRobot classes provides more methods to overide:

o disabledInit(), autonomousInit(), teleopInit()

called when the robot enters the given modeo disabledPeriodic(), autonomousPeriodic(), teleopPeriodic()

called approx. every 10 mso disabledContinuous(), autonomousContinuous(), teleopContinuous()

called as fast as the robot cano The IterativeRobot provides the main loop for

you, and calls the appropriate functionso You need to design your own state machine to

execute a sequence of actions

Displaying Diagnostic Output Option 1: System.out.println()

o This is the usual way to display text output from a Java program

o Example: System.out.println("current speed is " + speed);

o To view the output, install the NetConsole viewero NetConsole requires the National Instruments

LabView libraries (installed from the FIRST DVD)

o Download NetConsole from  

Page 18: First fare 2010 java-introduction

http://first.wpi.edu/Images/CMS/First/NetConsoleClient_1.0.0.4.zip

o More info is at http://first.wpi.edu/FRC/frccupdates.html (Team Update 4.0)

Option 2: Driver Station User Messageso There is a six line area for User Messages on the

Driver Stationo You can display text in it using

the DriverStationLCD classo Example (displays "Shoot the Ball!" on line 2,

column 1):   DriverStationLCD dsLCD = DriverStationLCD.getInstance();   dsLCD.println(DriverStationLCD.Line.kUser2, 1, "Shoot the Ball!");   dsLCD.updateLCD();

Option 3: SmartDashboardo This is a new class for 2011, currently only in

betao More info in the next portion of the presentation