Changes between Initial Version and Version 1 of ControlSystems/SoftwareTeam/Training/GettingStarted/IntroRobotJava


Ignore:
Timestamp:
Oct 7, 2019, 9:30:56 PM (6 years ago)
Author:
David Albert
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • ControlSystems/SoftwareTeam/Training/GettingStarted/IntroRobotJava

    v1 v1  
     1= Java for FRC Robotics =
     2Writing Java programs to control a robot is similar to the Java programming you've already learned; there are three key differences:
     31. The program you write must be transferred to the robot's computer (the roboRIO) where it will run
     42. FIRST and WPI provide a framework that your robot program must run within; the framework manages many aspects of the robot for you.
     53. WPI also provides a rich library of pre-written classes called WPIlib that makes robot programming faster and easier.
     6
     7We write robot software in VSCode just as we did for Java, but we'll make use of the WPILib extensions to create, build, and run our robot programs.  The WPILib extension is available via the W icon in the toolbar.  Click on the icon and then:
     8* Select Create a new project
     9* Select Project Type->Template->java->Iterative Robot
     10* Select a New Project Folder  and select (or create and then select) Documents\Robot Projects
     11* Enter project name: Xbox1
     12* Enter team number: 2537
     13* Press Generate Project
     14* At the dialog select Yes (Current WIndow)
     15The WPILib extension then creates a new Robot project for you.  The project contains many files and they're listed and organized in the left tree.  The file we're intersted in is src->main->java->Robot.java  open that file by double-clicking on it.
     16
     17The Robot.java class that was created for you contains the minimal set of functions required for a robot program operating in the WPIlib framework.  The functions include:
     18* robotInit() - called once when the robot starts
     19* robotPeriodic() - called periodically (e.g. every 20ms)
     20* autonomousInit() called one when the robot first enters autonomous mode
     21* autonomousPeriodic() - called periodically (e.g. every 20ms) while the robot is in autonomous mode
     22* teleopPeriodic() - called periodically while robot is in teleoperated mode
     23* testPeriodic() - called periodically while robot is in test mode
     24
     25You will put your setup code in the Init() functions and the code that should run repeatedly in the Periodic() functions.
     26
     27Modify the newly created program as follows:
     28* Add {{{ import edu.wpi.first.wpilibj.XboxController; }}} to the imports
     29* In the Class definition where variables are defined, add {{{   private XboxController xbox; }}}
     30* In the function robotInit() add: {{{ xbox = new XboxController(0); }}}
     31* In the function robotPeriodic() addd: {{{ SmartDashboard.putNumber("Left Joystick X", xbox.getX()); }}}
     32
     33Use the WPILib icon to build your new program: W->Build Robot Code
     34
     35
     36== Start with an example
     37The best way to learn about robot programming a robot is to start with a simple example program, run it, study what it does, and incrementally expand its functionality.  The WPILib software you installed includes example programs that you can compile and run on a RoboRIO.  Review [https://wpilib.screenstepslive.com/s/currentCS/m/79833/l/941601-vs-code-basics-and-wpilib-in-vs-code how to use VSCode] and then try [https://wpilib.screenstepslive.com/s/currentCS/m/79833/l/932465-creating-a-new-wpilib-project-in-vs-code creating a new robot project].
     38
     39* WPILib provides [https://wpilib.screenstepslive.com/s/currentCS/m/java/l/599697-choosing-a-base-class 3 frameworks] for building robot programs.  Build your first program using the !TimedRobot (previously had been !IterativeRobot) framework as described [https://wpilib.screenstepslive.com/s/currentCS/m/java/l/145307-creating-your-benchtop-test-program here].
     40
     41   * Connect your laptop to the RoboRIO USB port
     42   * Connect your joystick or xbox controller to another USB port on your laptop
     43   * Launch the NI Driver Station Software.  For details see [https://wpilib.screenstepslive.com/s/4485/m/24192/l/144976-frc-driver-station-powered-by-ni-labview here]
     44   * Confirm that the software detects your joystick/controller and responds to button presses and stick movement
     45   * Use Microsoft Internet Explorer (not Chrome or Firefox) to connect to the RoboRIO's web interface (usually at http://172.22.11.2) and confirm that you have connectivity with the RobORIO
     46   * Create a test project and follow [https://wpilib.screenstepslive.com/s/currentCS/m/79833/l/932465-creating-a-new-wpilib-project-in-vs-code these instructions] to build, load, and run it on your RoboRIO/Robot
     47
     48**Congratulations**, you've just built and run your first robot program.
     49
     50* Create another WPILib project based on the !TimedRobot framework
     51   * Study an example program.  This is a simple program for one of our test robots: Peanut 2. 
     52      * 2-wheel-drive (2WD) robot with two CIM motors driving plaction wheels
     53      * Motors are controlled by Talon SRX smart motor controllers; these are networked to the roboRIO (robot control computer) using CAN bus and are at addresses 3 (left motor) and 4 (right motor)
     54      * An ultrasonic sensor for forward collision avoidance connected to roboRIO digital I/O pins (DIO) 0 and 1
     55      * A USB camera so you can drive even when you can't see the robot
     56      * The driver controls the robot using the two analog sticks on an X-box game controller
     57   * Copy the program below over the default Robot.java created by the framework
     58   * Use the WPILib->Manage Vendor Libraries->Install New Libraries Offline->select the CTRE Framework
     59{{{
     60
     61package frc.robot;
     62
     63// Import the classes of objects you will use
     64import edu.wpi.first.wpilibj.TimedRobot;
     65import edu.wpi.first.wpilibj.XboxController;
     66import edu.wpi.first.wpilibj.GenericHID.Hand;
     67import edu.wpi.first.wpilibj.Timer;
     68import edu.wpi.first.wpilibj.drive.DifferentialDrive;
     69import com.ctre.phoenix.motorcontrol.can.*;
     70import edu.wpi.first.wpilibj.Ultrasonic;
     71import edu.wpi.first.wpilibj.CameraServer;
     72
     73import edu.wpi.first.wpilibj.livewindow.LiveWindow;
     74
     75import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
     76import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
     77
     78/**
     79 * The VM is configured to automatically run this class, and to call the
     80 * functions corresponding to each mode, as described in the TimedRobot
     81 * documentation. If you change the name of this class or the package after
     82 * creating this project, you must also update the build.gradle file in the
     83 * project.
     84 */
     85public class Robot extends TimedRobot {
     86  // Create instances of each object
     87  private static final String kDefaultAuto = "Default";
     88  private static final String kCustomAuto = "My Auto";
     89  private String m_autoSelected;
     90  private final SendableChooser<String> m_chooser = new SendableChooser<>();
     91  private XboxController xbox;
     92  private Timer timer;
     93  private WPI_TalonSRX m_rearLeft;
     94  private WPI_TalonSRX m_rearRight;
     95  private DifferentialDrive m_drive;
     96  private boolean    f_safetyStop;
     97  private Ultrasonic f_ultrasonic;
     98
     99  /**
     100   * This function is run when the robot is first started up and should be
     101   * used for any initialization code.
     102   */
     103  @Override
     104  public void robotInit() {
     105    // initialize the objects and connect them to their underlying hardware
     106    m_chooser.addDefault("Default Auto", kDefaultAuto);
     107    m_chooser.addObject("My Auto", kCustomAuto);
     108    SmartDashboard.putData("Auto choices", m_chooser);
     109    xbox = new XboxController(0);
     110    timer = new Timer();
     111    m_rearLeft = new WPI_TalonSRX(4);
     112    m_rearRight = new WPI_TalonSRX(3);
     113    m_drive = new DifferentialDrive(m_rearLeft, m_rearRight);
     114    f_ultrasonic = new Ultrasonic(1,0); // ping, echo
     115    f_ultrasonic.setAutomaticMode(true);
     116    f_ultrasonic.setEnabled(true);
     117    CameraServer.getInstance().startAutomaticCapture();
     118}
     119
     120  /**
     121   * This function is called every robot packet, no matter the mode. Use
     122   * this for items like diagnostics that you want ran during disabled,
     123   * autonomous, teleoperated and test.
     124   *
     125   * <p>This runs after the mode specific periodic functions, but before
     126   * LiveWindow and SmartDashboard integrated updating.
     127   */
     128  @Override
     129  public void robotPeriodic() {
     130  }
     131
     132  /**
     133   * This autonomous (along with the chooser code above) shows how to select
     134   * between different autonomous modes using the dashboard. The sendable
     135   * chooser code works with the Java SmartDashboard. If you prefer the
     136   * LabVIEW Dashboard, remove all of the chooser code and uncomment the
     137   * getString line to get the auto name from the text box below the Gyro
     138   *
     139   * <p>You can add additional auto modes by adding additional comparisons to
     140   * the switch structure below with additional strings. If using the
     141   * SendableChooser make sure to add them to the chooser code above as well.
     142   */
     143  @Override
     144  public void autonomousInit() {
     145    m_autoSelected = m_chooser.getSelected();
     146    // autoSelected = SmartDashboard.getString("Auto Selector",
     147    // defaultAuto);
     148    System.out.println("Auto selected: " + m_autoSelected);
     149    timer.reset();
     150    timer.start();
     151  }
     152
     153  /*public void teleopInit() {
     154
     155  }*/
     156
     157  /**
     158   * This function is called periodically during autonomous.
     159   */
     160  @Override
     161  public void autonomousPeriodic() {
     162    if (timer.get() < 2.0) {
     163      m_drive.curvatureDrive(0.1, 0.0, false);
     164    }
     165    else
     166    {
     167      m_drive.curvatureDrive(0.0, 0.0,false);
     168    }
     169    switch (m_autoSelected) {
     170      case kCustomAuto:
     171        // Put custom auto code here
     172        break;
     173      case kDefaultAuto:
     174      default:
     175        // Put default auto code here
     176        break;
     177    }
     178  }
     179
     180  /**
     181   * This function is called periodically during operator control.
     182   */
     183  @Override
     184  public void teleopPeriodic() {
     185
     186    // Use front-mounted ultrasonic sensor to stop robot
     187    // if it gets too close to an obstacle
     188    double f_range = f_ultrasonic.getRangeInches();
     189    if (f_ultrasonic.isRangeValid()) {
     190       if ((f_range < 15.0) && !f_safetyStop) {
     191          System.out.println("Safety stopped due to front obstacle");
     192          f_safetyStop = true;
     193       } else if (f_range >= 15.0 && f_safetyStop) {
     194          System.out.println("Resuming...");
     195          f_safetyStop = false;
     196       }
     197    }
     198
     199    // Use controller joysticks to set drive speed, but
     200    // safety stop if too close to an obstacle
     201    double leftSpeed  = -0.5*xbox.getY(Hand.kLeft);
     202    double rightSpeed = -0.5*xbox.getY(Hand.kRight);
     203    // If there's an obstacle in front of us, don't
     204    // allow any more forward motion
     205    if (f_safetyStop &&
     206        (leftSpeed > 0.0) && (rightSpeed > 0.0)) {
     207       m_drive.stopMotor();
     208    } else {
     209      // otherwise, set motors according to joysticks
     210       m_drive.tankDrive(leftSpeed, rightSpeed);
     211    }
     212    Timer.delay(0.01);
     213  }
     214
     215  /**
     216   * This function is called periodically during test mode.
     217   */
     218  @Override
     219  public void testPeriodic() {
     220    // LiveWindow.run();
     221  }
     222}
     223
     224}}}
     225
     226* Sample code for Hazelnut (peanut robot) is [wiki:ControlSystems/SampleCode/Hazelnut here]
     227* A sample program to use ultrasonic sensors is [wiki:ControlSystems/SampleCode/Ultrasonic here]
     228* A sample program to use xbox controllers is [wiki:ControlSystems/SampleCode/XboxController here]
     229* You can learn more about FRC robot programming [https://frc-pdr.readthedocs.io/en/latest/index.html here]
     230* You can learn more about game controllers [https://github.com/MTHSRoboticsClub/Documentation/wiki/Drive-Controller-Comparison here]
     231
     232* Note: you can also program and operate a peanut robot wirelessly:
     233  * Find the Peanut's !WiFi access point and connect to it; the default password is "password"
     234  * From within VSCode, choose WPILib->Deploy Robot Code
     235  * Launch the Driver Station
     236  * Enable and then start driving!
     237
     238* Note: the sample program assumes two !TalonSRX motor controllers at IDs 3 and 4.  You can set them using the CTRE Phoneix Tuner
     239* Note: the !RoboRIO web web interface is available via browser at 10.25.37.2