frc java - team up nextteamupnext.com/wp-content/uploads/2014/08/frc_java_3528_2014.pdf · •due...

63
FRC JAVA PRESENTED BY TEAM UP NEXT – FIRST TEAM 3528 TEAMUPNEXT.COM

Upload: vanque

Post on 01-Aug-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

FRC JAVAPRESENTED BY TEAM UP NEXT – FIRST TEAM 3528

TEAMUPNEXT.COM

PRELUDEIN THE BEGINNING…

EXPECTATIONS

• This session assumes some Java knowledge or that you’re pursuing that

knowledge soon

• You cannot learn a programming language in 3 hours

• To be a great programmer on your FRC team it is crucial you gain knowledge

of the electrical and controls

• Learning to code is difficult but rewarding

ADVICE

• Don’t be afraid to experiment, to explore, to try things, to learn things on your

own

• CAVEAT: Triple check your code when running it on a robot or in a live test

environment

• Run robot code for the first time with motors disconnected and observe (even

measure) the speed controller outputs

MORE ADVICE

• Learn the Controls!

• Controls people make better FRC Coders

ACT IPURE JAVA

WHAT IS JAVA?

• Java is an object oriented programming language that compiles its programs

to byte code and executes within a Java virtual machine.

• The Java virtual machine enables the program to be (theoretically)

architecture agnostic.

WHY USE JAVA?

• Provides a simpler approach to multi- architecture programming.

• To some degree provides a portable platform to run executable code.

• Due to Java’s ability to port the virtual machine to multiple architecture’s, Java

is found in devices ranging from toasters, TV’s, mobile phones, cameras, blue-

ray players and more.

THE BASICS OF JAVA

• Java programs are objects which are instances of a class or classes.

• Java programs are essentially created by compiling through the Java Development Kit (jdk)

• Java supports the following primitive data-types:

• boolean (true / false)

• byte (-127-- 128)

• integer (-2,147,483,648 -- 2,147,483,647)

• long (-2^63 -- 2^63 -1)

• float (32 bit)

• double (64 bit)

• char (16 bit Unicode)

HOW SIMPLE IS IT TO WRITE A JAVA PROGRAM? WHAT DO I NEED?

• The Java Runtime Environment – JRE

• The Java Development Kit – JDK

• Minimally a text editor such as notepad. Those beginning may want an IDE such as

• Eclipse

• NetBeans

• IntelliJ

• Jcreator

• JBuilder

JAVA PROGRAMMING

• Source code for a Java program (or class), the un-compiled program, is

typically stored in text files ending with the extension .java.

• Compiled Java classes (or programs) are stored using the file extension .class.

• Sometimes the source packages are stored in executable formats with the

extension .jar. Typically they are executed through the following command

“java –jar <jarname>”.

THE BASIC PROCESS OF DESIGNING A JAVA PROGRAM (IN SUMMARY)

• Code

• Compile (through the JDK)

• Execute (through the Java VM)

WHAT DOES A SIMPLE JAVA PROGRAM LOOK LIKE?

Program Code Output – Command Window

import java.lang.*;

public class myProgram {

public static void main(String[] args) {

System.out.println(“Hello world!”);

}

}

Hello world!

DEFINING VARIABLES AND CONSTANTS

• Variable(data type) => attribute name ;

• int x;

• float y;

• char z;

• Constant => final attribute name = value;

• final int THISYEAR = 2011;

JAVA SYNTAX USAGE

• Simple assignments listed above by using the = sign or small expression.

• int e = 1;

• String str = “Hello”;

• int j = 1 + e;

• Invoking procedures

• Procedure name (Optional parameters)

• printMyName(nameIn);

• printMyName();

JAVA SYNTAX – MATH OPERATORS

• + for addition

• - for subtraction

• * for multiplication

• / for division

• % (modulus) the remainder after division

• Math.sqrt(x) the square root of a number x.

• Math.abs(x) the absolute value of a number x.

• Math.sin(x), Math.cos(x), Math.tan(x)

JAVA SYNTAX – COMPARISON OPERATORS

• Comparison operators will return true (when a value falls within the comparison parameter) or false when it

does not.

• < less than

• <= less than or equal to

• == equal to

• >= greater than or equal to

• > greater than

• != not equal

• To help compare ranges you can use the following statements with in your statements.

• && implies AND

• || implies OR

JAVA SYNTAX

• Compound syntax

• Selection statements

• if

• if / else

• switch / case

• Repetition / iteration

• while

• do / while

• for

JAVA SYNTAX - CONTINUED

• Methods are procedures that are called upon can take a parameter, but are

required to return a data value.

• Attribute functionname (parameter list)

• int addOneToX(int x) { x = x+1; return x; }

• String helloName(String nameIn) {

return “Hello “ + nameIn; }

JAVA SYNTAX - ARRAYS

• Arrays are collections of a single data-type either in a single dimension or a

multi-dimension.

• Array sizes are declared before the array can be used.

• Things can be placed into a direct index and thus can be retrieved through

that index.

ARRAY - SAMPLE

• int myNumbers[] = new Int[4];

• myNumbers[0] = 4;

• myNumbers[1] = 2;

• myNumbers[2] = 3;

• myNumbers[3] = 5;

• System.out.println(myNumbers[0]);

• -----------Output--------------

• 4

OTHER JAVA STATEMENTS

• Exceptions – Occur when a input or error in processing occurs in which the

program (or in rare circumstances) the java virtual machine is unable to cope

with.

• In a “perfect world”, make sure that inputs are within in processing range and/or data-

type.

• Or use a try / catch statement.

OVER JAVA STATEMENTS

• Casting – The ability to force a data type into another data type. This is

different from parsing or converting.

• Take and integer num1 and a double num2. Convert num1 to num2.

• double num2 = (double) num1;

• int num1 = (int)num2;

• In a class scenario.

• Jaguar rotateMtr = (Jaguar)getSpeedController();

JAVA STORES LIBRARIES INTO CLASSES WHICH ARE STORED INTO PACKAGES.

• Typically called through the import command.

• import java.lang.*;

• import java.io.*;

• import java.net.*;

WHAT IS A CLASS AND HOW IS IT USED?

• “A class is an unstructured type that encapsulates a fixed number of data

components (data members) along with the functions (called member functions

or methods) that manipulate them.” - CST 271 Notes.

CLASS EXAMPLE

• Take a house for example. What describes a house?

• Size

• Number of bedrooms

• Number of bathrooms

• Address

• Color

• Does it have a garage…? If so how big is it?

CLASS – HOUSE EXAMPLEpublic class house {

public String color;

public String address;public double totalSize = 0.0;

public int numberOfBedrooms = 0;

public int numberOfBathrooms = 0;public boolean doesGarageExist = false;

public double sizeOfGarage = 0.0;

//End variable declaration.

public house() {

//This is the constructor for the object.}

public String returnSumary() {String out = “The house at “ + this.address + “\n”;

out += “has “ + this.numberOfBedrooms + “ number of bedrooms\n”;

out += “ and “ + this.numberOfBathrooms + “ number of bathrooms\n”;

if(this.doesGarageExist) {

out += “This house contains a “ + this.sizeOfGarage + “ sq. feet garage\n”;}

out += “The house color is “ + this.color + “\n”;out += “The house contains “ + this.totalSize + “ square feet”;

return out;

}}

IMPLEMENT AN INSTANCE OF THE HOUSE CLASS

Code Output

public static class houseProgram {

public static void main( String args[] ){

house myHouse = new house();

myHouse.color = “pink”;

myHouse.totalSize = 1200.5;

myHouse.numberOfBedrooms = 3;

myHouse.doesGarageExist = true;

myHouse.sizeOfGarage = 12.0;

myHouse.address = “123 Main Street”;

System.out.print(

myHouse.returnSummary() );

}

}

The house at 123 Main Street.

has 3 bedrooms

and 2 bathrooms.

The house contains a 12.0 sq. feet garage.

The house color is pink.

The house contains 1200.5 square feet.

CLASS INHERITANCE

• Class inheritance is the process of extending a parent class.

• Example creating a mansion class which extends from the house class

• public class mansion extends house

• In this fashion, methods and certain variables from the parent class are

brought into the mansion class. You can build upon those or override them.

JAVA VARIABLE/PROCEDURE/FUNCTION/CLASS RESTRICTIONS

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

(default) Yes Yes No No

private Yes No No No

protected Yes Yes Yes No

public Yes Yes Yes yes

ECLIPSE INSTALL DEMO

RESOURCES

• http://teamupnext.com/java

• Bucky’s Room

• Beginner: https://buckysroom.org/videos.php?cat=31

• Intermediate: https://buckysroom.org/videos.php?cat=25

• Udemy (Java Tutorial for Complete Beginners)

• https://www.udemy.com/java-tutorial/#/

MORE RESOURCES

• The official Java tutorials

• http://docs.oracle.com/javase/tutorial/

• Purdue (CS 18000 - Problem Solving and Object Oriented Programming)

• https://www.cs.purdue.edu/news/Onlinecourse.html

• https://selfservice.mypurdue.purdue.edu/prod/bzwsrch.p_catalog_detail?subject=CS&te

rm=CURRENT&cnbr=18000

ACT IIFIRST JAVA

FRC JAVA ROBOTICS – WHAT YOU WILL NEED

• ? (lots of unknowns for 2015)

• Java SE (JDK 8):

• http://www.oracle.com/technetwork/java/javase/downloads/index.html

• Eclipse (Luna – Java EE):

• http://eclipse.org/downloads

• FRC Java Plugin from WPILIB

• ? (unknown until kickoff)

FRC JAVA – BASE CLASSES AND MORE

• SimpleRobot (now SampleRobot)

• IterativeRobot

• All roads lead to BaseRobot

• Command Based (model - not a base class)

SIMPLE/SAMPLE ROBOT

• The SimpleRobot class is the simplest to understand as most of the state flow is directly visible

in your program

• Your robot program overrides:

• operatorControl()

• autonomous()

• Methods that are called by the base at the appropriate time.

• NOTE: These methods are called only called once each time the robot enters the appropriate mode and

are not automatically terminated.

• Your code in the operatorControl method must contain a loop that checks the robot mode in

order to keep running and taking new input from the Driver Station.

SIMPLE ROBOT DEMO

ITERATIVE ROBOT

• The Iterative Robot base class assists with the most common code structure by handling the state transitions and

looping in the base class instead of in the robot code. For each state (autonomous, teleop, disabled, test) there

are two methods that are called:

• Init methods

• The init method for a given state is called each time the corresponding state is entered (for example, a transition from disabled to

teleop will call teleopInit()). Any initialization code or resetting of variables between modes should be placed here.

• Periodic methods

• The periodic method for a given state is called each time the robot receives a Driver Station packet in the corresponding sta te,

approximately every 20ms. This means that all of the code placed in each periodic method should finish executing in 20ms or less.

• The idea is to put code here that gets values from the driver station and updates the motors. You can read the joysticks and other

driverstation inputs more often, but you’ll only get the previous value until a new update is received. By synchronizing with the

received updates your program will put less of a load on the cRIO CPU leaving more time for other tasks such as camera

processing.

ITERATIVE ROBOT DEMO

COMMAND BASED

• While not strictly a base class, the Command based robot model is a method for

creating larger programs, more easily, that are easier to extend.

• There is built in support with a number of classes to make it easy to design your

robot, build subsystems, and control interactions between the robot and the operator

interface.

• In addition it provides a simple mechanism for writing autonomous programs. The

command based model is described in detail in the Command Based Programming

manual.

SUBSYSTEMS

• Subsystems are classes that extend “Substem”

• Subsystems model your robot

• DriveTrain

• Arm

• Shooter

• Subsystems contain the code that does stuff

• Subsystems contain / reference the objects that represent your controls

COMMANDS

• Commands are classes that extend “Command”

• Commands are shells that run based on operator or other inputs or decisions

• Commands require subsystems

• Command call code in subsystems

COMMAND GROUPS

• Command Groups are classes that extend “CommandGroup”

• Command Groups are simply groups of commands

• Command Groups act like commands

• Commands in a command group can be run two ways:

• Series

• Parallel

• Very useful for autonomous

OI == OPERATOR INTERFACE

• OI is where your human interface objects go

• Joysticks

• Joystick Buttons

• OI is also where SmartDashboard lives

• In OI, buttons are mapped to commands

ROBOT MAP

• RobotMap is a class that instantiates all your robot controls objects

• Class objects define your physical controls

• RobotMap is referenced when you need to access one of these objects

• The init() method is where the objects are instantiated

ROBOT CLASS

• The Robot class extends IterativeRobot

• The robotInit() method is where it all starts:

• Each subsystem is brought into existence (instantiated)

• The OI is instantiated

• autonomousInit()• Sets up the autonomous command to run – put it on the queue

• Turn off motor safety

• autonomousPeriodic()• Runs the scheduler which runs the commands

ROBOT CLASS CONTINUED

• teleopInit()

• Cancel autonomous

• Initialized the robot for teleop

• Turn on Motor Safety

• teleopPeriodic()

• Runs the scheduler which runs the commands

COMMAND BASED: ROBOT BUILDER DEMO

• Our Robot

• DriveTrain

• Two Speed Controllers

• Tank Drive

• Leftstick and Rightstick on xbox controller

• Elevator

• Spike Relay

• Limit Switch

• Joystick Button

UP NEXT 2014 CODE WALKTHROUGH

• Just the hightlights

DEBUGGING

• Debugger

• Println’s

ADDING A PRINTLN TO THE CODE

• At any point in the java program, you can add a:

System.out.println();

• This will allow you to print messages, variable contents, or other useful info to

the console output

RESOURCES

• http://teamupnext.com/java

• http://wpilib.screenstepslive.com

ACT IIIRECOMMENDATIONS AND TOOLS

SOURCE CODE VERSION CONTROL

• Highly recommend using a version control system:

• GIT (our favorite)

• Subversion

• CVS

• Jazz SCM

• Good way to keep backups of your code

• Useful for reverting to previous versions

• Multi Developers

MINIMALLY…

• Backup your code often

• Use cloud storage:

• Dropbox

• Box

• Google Drive

• OneDrive (formerly SkyDrive)

COMMENTS AND DOCUMENTATION

• Useful Comments are essential

• Document your Controls

• Joystick mappings

• Control channels

• Pneumatics layout

USEFUL TOOLS

• notepad++

• net console

• putty

• Github client

• Git for Windows (git scm)

KNOW WHICH CODE IS RUNNING

• This scenarios catches more people

• You coding away, you push your code, your flux capacitor still doesn’t work

• More coding

• More pushing code

• Nothing

• Runs away screaming!

• Are you absolutely sure your running the code you think you’re running

• Save your sanity

• Always put a println at the top of your code just after the robot initializes

• We use something like: System.out.println("====> JeffBot <====");

• Make it a habit to always look for this after pushing code

2015 JAVA: ME TO SE – TEAM 694

• http://www.slideshare.net/boyarsky/java-5-through-8-and-eclipse

2015 CONTROLS – TEAM 358

• http://www.team358.org/files/programming/ControlSystem2015-2019/

QUESTIONS?

• We’re always happy to help:

• http://teamupnext.com/contact-us

• Many other great teams use Java

[email protected]

THE ENDTHANK YOU!