Download presentation
Presentation is loading. Please wait.
1
Java Code Class Team 2992
2
How to write names with several words:
First off – Syntax!! “word” is not equal to “Word” or to “WORD” Syntax is the set of rules that defines how symbols can be combined to be acceptable for the programming language. In java the syntax must be EXACTLY the same. In Java, semicolons are like periods – the end of sentences. How to write names with several words: Camel Case – capitalize each consecutive word. Ex: camelCaseExample Underscore – put an underscore between each word. Ex: under_score_example
3
Java basics: Simple and complex data types
Simple Data types: Numbers Booleans Strings Characters (Char) Complex Data types (We’ll learn later): Arrays Objects Write on board
4
Simple Data types They are variables that hold only one value at any given time. In math you have the variable x. x can be any value imaginable, but it is only one value at a time. Graph of y = x X Y 1 2 X does not hold both 1 and 2 at the same instant of y. (function of x)
5
Java basics: variable types
Int – integer, no decimals. Positive/Negative/0 Boolean – true/false variable Float – 32 bit decimal (Basically obsolete) Double – 64 bit decimal, better than float String – words/letters, must go in “ ”, not often used in FRC -2, -1, 0, 1, 2 true, false Float = about 7 decimals Double = 15 decimals “This is a String”
6
Declaring a variable First, state the variable types and modifiers needed. Then, name the variable. Use an assignment operator (=) and then the value of the variable. ; int num1 = 23; double num2 = ; String string = “words”; Boolean what = true;
7
Operators An operator is a symbol that tells the computer to perform a specific action on the values the operator is assigned to. Assignment operator = (Gets the value of) Math Operators: + (addition) - (subtraction) * (multiplication) / (division) Boolean Operators == (equals) != (Not equal) < <= > >= Int integer = 10; Boolean variable = true; String word = “Hello”;
8
Operator practice int first = 5; int second = 23; first = first + second What does first equal now? 28 int first = 10; Int second = 5; int third = first / second What does third equal now? 2 Boolean one = ( 5 > 2); true Boolean two = (5 < 2); false Boolean three = (5 == 5); true Boolean four = (5 != 5); false
9
Another operator Ex: 5/2 = 2 R 1 so 5%2 = 1
Modular (Mods) – Remainder (%) A%B : A/B = # r(Answer) Best way to find is a number is even or odd. #%2 If even = 0 If odd = 1 Ex: 5/2 = 2 R 1 so 5%2 = 1 10%2 = 0 10/2 = goes in evenly 11%2 = 1 11/2 = 5 r has a remainder 20%3 = 2 20/3 = 6 r2 ----has a remainder ???
10
Conditional Operators
&& (and) (true && true) -> true (true && false) -> false (false && true) -> false (false && false) -> false || (or) (true || true) -> true (true || false) -> true (false || true) -> true (false || false) -> false If(this && that){ do code 1 } If(this || that){ do code 2
11
Java basics: if statement
If/else if statements: uses a Boolean condition to determine what code gets run. Else statements: code block runs when previous If statements were false int variableName = 10; if(variableName <5){ code to be run if condition is true } else if(variableName<10){ code to be run if this condition is true code in 1st If did not run. else{ Don't need a condition. If all other if/else if statements failed, this code runs Integer Variable Code Block
12
… and yet another operator
? Conditional operator Another type of if statement If (a>b){ max = a; } else{ max = b; } max = (a>b)? a : b;
13
String Concatenation System.out.println(“string to print to console”);
Extra – just for the game we’re gonna do next String concatenation – putting strings together with + System.out.println(“string to print to console”); String one = “My ”; String two = “ name ”; String three = “ is ”; System.out.println(one + two + three + “ Hayley”); Console: My name is Hayley
14
More Vocabulary Method – Like a function. Has a name and defines a set of instructions to be used when the function name is called. Method Call addMethod(10, 2); public int addMethod(number1, number2){ return (number1+number2); } Argument Parameter Method Declaration Notice the declaration used public and int. This means the method is available from any file and that the method returns an integer value Parameters are the variables or placeholders for any value needed to run the code. They make the method more generalized. Arguments are the actual data that is put in the ( ) of the method call that are held as the parameters’ values for the method.
15
Return return – replaces the method call with the returned value. No code in the method runs after the return. int sum = addMethod(10,2); public addMethod(number1, number2){ return (number1+number2); } 12; The addMethod runs and returns the value 12. The value 12 replaces the addMethod call
16
Types of FRC built in methods
Init – it runs one time when the things starts up. Periodic: the code block reruns every 20 milliseconds. teleopInit(){ //code block runs when teleop starts. Use to end auto and //reset some hardware } teleopPeriodic(){ //code block runs every 20 milliseconds during the teleop //period. It runs periodically.
17
Java basics: Arrays It is a 0-indexed ordered list
Index – the place of a specific element in an array. Arrays use bracket notation [ ] You can access any element of the array using bracket notation. Array.length returns the number of elements in the array … so array.length-1 returns the last element in the array. ArrayList<TypesInArray>arrayName; arrayName = [element1, element2, element3]; Index : getElement1 = arrayName[0]; getLastElement = arrayName[arrayName.length-1];
18
Java basics: objects The instance of a class that stores the state of a class. public class Cat ( ) { int age; public Cat( int catsAge) { age = catsAge; } public void speak( ){ System.out.println(“Meow!!”); public static void main(String [ ] args){ Cat kitty = new Cat(5); kitty.speak(); Class Constructor Main Object Method
19
Java Basics: Object Terminology
Class: a blueprint for how a data structure should function. – A grouping of existing things. A class includes things that all objects of that type should have. Ex: A bike has some things about it that are the same for all bikes (Wheels, handlebars, seat). Constructor: instructs the class how to set up the initial state of an object. Inheritance: allows one class to use functionality defined in another class. Made by the “extends” keyword. Main: The code in that method runs when the program is executed.
20
Extends extends – says this class uses all of the components of a class that is already made. public class Cat extends Animal() { int age; public Cat(int catsAge){ age = catsAge; super(“mammal”); //calls Animal’s constructor } public static void main(String [ ] args){ Cat kitty = new Cat(5); kitty.whatKind(); public class Animal(){ String type; public Animal(String animalType){ type = animalType; } public String whatKind(){ System.out.println(“Your animal is a “ + type);
21
Java basics: Variable Modifiers
public – Allows the variable to be accessed from any file that the class is also available. private – Makes the variable exclusive to that one class. final – Makes constants out of variables. Can’t be assigned different values after the 1st time. static – Variable is common to the whole class, not just 1 object. void – Used mostly for functions. No value is returned. For more information:
22
Java Basics: declaring and Initializing variables that are objects
Declare a variable Goes in the public Class() Need to include the variable modifier(s) Initialize a variable Goes in init() (within the class) Don’t need to include variable modifier(s) public static void init() { rBDriveMotor = new WPI_TalonSRX(3); driveTrainSolenoid = new Solenoid(0, 0); leftmotors = new ArrayList<WPI_TalonSRX>(); driveTrainleftDriveEnc = new Encoder(2, 3, false, EncodingType.k4X); navx = new AHRS(SPI.Port.kMXP); } public class RobotMap { public static WPI_TalonSRX rBDriveMotor; public static Solenoid driveTrainSolenoid; public static ArrayList<WPI_TalonSRX>leftmotors; public static Encoder driveTrainleftDriveEnc; public static AHRS navx; } Initializing solenoid //(device #, port #) EncodingType.k4x – SPI.Port.kMXP - All variables must be declared and initialized, but some can be declared and initialized in 1 line. Mostly need to do initialize a variable for hardware in RobotMap (where all electronics are made in code).
23
Java Basics: While loops
Not used as often as for loops, especially in FRC Initialization – Create a variable to hold the number of times the code is looped. Stop Condition – A condition where when true, the code loops again, and when false, the loop ends. Post Condition – Something that runs at the very end of the loop’s code block. Usually updates the initialization Boolean condition = true; Int counter = 0; while(condition){ //code to be run counter = counter +1; } Say “While the condition is true, run the code in the block.” As soon as the condition reads false – the loop ends This is above example is a infinite loop.
24
Java Basics: For Loops For loop: This type not often used in FRC. (good for light code) 1 2 3 4 5 6 7 8 9 Initialization Stop Condition Post Condition For(int i=0; i<10; i++){ // code block to run 10 times System.out.println(i); } Notice 3 things that are the same between for and while loops?? Does NOT include 10. Once i becomes 10, the stop condition is false so the loop ends.
25
Java Basics: Enhanced for loop
Can be used in FRC Used for arrays and objects. You make a new variable (in this case “motor”) including the type (“WPI_TalonSRX"). Then you put the : and the array or object name. What this does is put each value in the array or object into the variable to run the code block, which should reference the variable to do something. for(WPI_TalonSRX motor : allMotors){ //code block to run; motor.set(0); } Say WPI_TalonSRX motor controller in the allMotors array.
26
Background What is Visual Studio?
It is a coding platform made by Microsoft, that FIRST is going to be used for this season. It is new this year. What did it used to be? The old coding platform was called Eclipse. Robot builder was connected to it, but I’ll talk about it later.
27
Java projects In Visual Studio, click the WPILIB button, make new project… Create a new folder (it will have the name of the project) Make a name for the bot. (Be descriptive, camelCase or under_score, No spaces).
28
Robot Builder Not yet added as an app on Visual Studio, will be before build season. Keep an eye on WPILIB or Chief Delphi for changes. It is a really cool, drag-and-drop application that makes the basics of your code. Since, it is not yet on VS, I added it to your laptop from my flash drive, or you downloaded it from the . It will create Eclipse projects, so you will have to “upgrade the Eclipse Project” under the WPILIB button.
29
Github!!! What is it? It is a website that you can use to share code with your team members. It uses something called git, which you use to “push” the code to Github. It’s free, so I suggest the team gets one, and each code member gets one as well.
30
What to do with github? How to make a repository (repo)
Go to the team account. Click the green button named “Make Repository” Name the file, choose public or private (I would do private during build season), and DO NOT make a readme file or gitignore. When to pull and push: If you are the only one working on the code, push at the end of the day, but don’t pull if no one else is editing it. If there are several people working on code, push at the end of the day and pull before you start writing any code.
31
Github continued In the terminal:
How to push to Github from Visual Studio: 1st time only, you need to add the git and Github extension packs To initialize and user name: Create local git repo Click on Source Control tab or type Go to Github and make a new repo (no ReadME or gitignore). Copy the link Go to VS and type: In the terminal: git config --global user. “ ” git config --global user.name “username” git init git commit –m”message” git remote add origin <link> git remote –v //verifies link to repo git push –u origin master //pushes code to github
32
Github continued How to pull from Github:
In the Terminal, put “git fetch” to see if there are any changes, without actually merging them into your code. If there are any changes that you want, type “git pull” which fetches and merges any changes to your code. If it needs a source, type “git fetch *remoteName*”
33
Coding Hierarchy OI, Robot, RobotMap Subsystems Commands
OI – Button assignments Robot – Where to name subsystems, and when to make certain code run. (periodic and init) RobotMap – Where the electronics are initialized OI, Robot, RobotMap Subsystems The only part of code that should touch the hardware and set values to the hardware. Also where you make the functions for the commands to call. Commands The part of code that calls the functions from the subsystems. Also determines when the code stops running.
34
How to set motor values Private final motor1 = RobotMap.motor1; Private final motor2 = RobotMap.motor2; Private final motor3 = RobotMap.motor3; Public void setMotor1to50Percent(){ motor1.set(0.5); } Public void setMotor2to30Percent(){ motor2.set(0.3); Public void setMotor3to100Percent(){ motor3.set(1); This would go in a subsystem inside the class but not in the periodic or the init.
35
Autonomous Autonomous commands are written in something called Command Groups. addSequential – it waits until the previous addSequential is finished before starting. addParallel – it runs until complete, other commands don’t wait for it to finish before starting. addSequential(new autoCmd(10, 0.5, 5)); addParallel(new otherAutoCmd(10,0.5,5));
36
Autonomous The code for autoDriveForward and autoDriveTurn are actually regular commands. You need to use parameters for speed, distance, and timeout. The speed is in decimal form and is the percentage of power to the motors The distance is how far you want the robot to go (can be length or angle) The timeout is how long you think the program will take to complete. This makes sure that part ends in case there is faulty hardware.
37
PID This is how the robot does autonomous.
You only need to do this once for each type of PID (driving in a straight line and turning) Typically you do this in the drivetrain subsystem, but can put it in other subsystems This is super complicated calculus – but there’s an easier way to deal with it: Trial and Error
38
PID P stands for proportion. You need to think Power, when testing, try to get the robot to overshoot the mark a little bit. I stands for integral. You hardly ever need to tweak this value. It’s almost always 0 D stands for derivative. You need to think Dampening. When testing, tweak the value until the robot hits the mark consistently. Order of dealing with values: P, D, never I (yes you could call it a PD controller) Another point: the values are between 1 and 0. Test out by the tenths.
39
Useful websites WPILIB is a FIRST library intended to help students. Use it!! Codecademy (make an account) - java This is really only helpful to grasp objects
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.