Lab Two: Loop, Input and Output
The computer programs that control an FRC robot all follow the same pattern: a loop. In each pass through the loop the following things happen:
- Input: read the sensors or the driver station controls
- Examples:
- How fast is the shooter wheel rotating?
- Read the direction and tilt of a joystick on the driver station.
- Examples:
- Process: decide what do with the information you obtained from the sensors.
- Examples:
- The shooter wheel is rotating fast enough, go to the code that advances the ball.
- The joystick is tilted forward all the way, go to the code that makes the robot go forward at full speed.
- Examples:
- Output: tell motors and relays what to do. The fancy term for "tell motor what to do" is actuate motor.
- Examples:
- start the motor that moves the belt until the shooter grabs the ball
- move both motors (left track and right track) at full speed.
- Examples:
We're going to write a program that runs on your computer and simulates these three steps. By pressing certain keys on your keyboard you will move a character on the screen.
- Your computer keyboard will be the input.
- Type 'a' and hit enter to move the symbol left
- Type 's' and hit enter to move the symbol right
- Type 'q' to quit
- Any other key you press will not move the symbol either left or right
- Type 'aaa' and hit enter. Do you understand why that happened?
- Your monitor (a command prompt window to be more precise) will be the output.
package labtwo;
/**
* @author Bogdan
*/
public class LabTwo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Decision.position = 20;
Decision.positionUpdated = true;
Decision.keepRunning = true;
printOutput();
while (Decision.keepRunning) {
int input = readInput();
decideMove(input);
printOutput();
}
}
public static void printOutput() {
if (Decision.positionUpdated) {
String formatString = "%" + Decision.position + "s";
String output = String.format(formatString, '|');
System.out.println(output);
}
}
public static int readInput() {
int readCharacter;
try {
readCharacter = System.in.read();
} catch (java.io.IOException e) {
readCharacter = -1;
System.out.println("IOException reading from input");
}
return readCharacter;
}
public static void decideMove(int keyPressed) {
switch (keyPressed) {
case 'a':
Decision.position--;
Decision.positionUpdated = true;
break;
case 's':
Decision.position++;
Decision.positionUpdated = true;
break;
case 'q':
Decision.keepRunning = false;
Decision.positionUpdated = false;
break;
case -1:
Decision.keepRunning = false;
Decision.positionUpdated = false;
break;
default:
Decision.positionUpdated = false;
}
}
public static class Decision {
public static int position;
public static boolean positionUpdated;
public static boolean keepRunning;
}
}