Getting Started on C++ and FRC Programming

The instructions for 2011 are at http://www.spartanrobotics.org/content/getting-started-frc-programming-under-linux.

Getting Started on C++ and FRC cRIO Programming

Jerry Morrison, January 2009 + June 2012

Background: cRIO Programming language choices
The National Instruments cRIO is the main robot CPU.
  1. C/C++ is what Team 971 uses. But it's not easy. C++ gives you enough rope to shoot yourself in the foot. We spent 3 hours debugging a segfault that was due to a compiler switch setting. We spent hours debugging a cRIO networking problem that was (we think) due to overwriting data beyond the end of memory nodes. Neither C++ nor VxWorks (the OS) help with mistakes like those. But C++ imposes no limitations other than a big tax on brain cells and pulling out your hair.
  2. Java is much easier to use. It does a lot more for you. It provides much better build errors, run time error info, and debugger support. It rules out dozens of ways to get bit. It enables "refactoring" and other high-level editing features. You can get stuff done faster. BUT Sun provided the wrong JVM (it was a matter of who they had available & interested to help FIRST) so that JVM can occasionally take 150 msec garbage collection pauses. That's unacceptable for a safety-critical, real-time program. Also that JVM is limited to Java v1.3 (no generics, enum, autoboxing, annotations, etc.). Although I wouldn't want to use that JVM in competition, it is good for learning and prototyping.
  3. LabView is a graphical data-flow programming environment designed by and for EEs. National Instrument is big on LabView. I'm told it makes some hard things easy and some easy things hard.
  4. Python or something else: It's possible to use other languages but AFAIK they haven't been successful in FRC. There's an experimental Python port but it's too slow. It's tempting to investigate D or C# or Android's Dalvik VM (which will run Java programs with GC pauses on the order of a couple milliseconds) or a JVM (if you find one) that supports the real-time spec for Java.
NI puts its efforts into LabView. They're OK with it running atop a 10 year old version of VxWorks and its C++ development tools, but that's not great for teams who use C++.
"FRC programming" vs. "971 FRC programming"
Begin with FRC programming as suitable for all teams.
"971 FRC programming" differs in:
  • gcc, Ruby scripts, and other custom development tools on GNU/Linux
  • FIT-PC
  • Austin's custom gyro board
  • AOS communications between these three CPUs
  • steering control loop techniques
  • ...
You might be better off setting up our custom development tools, or the standard WindRiver Workbench (built on a very old version of Eclipse plus WindRiver's overcomplicated plugins), or both. Most likely both. You'll need WindRiver Workbench to get the sample programs.
For the other items above, just put them off to the future.
Docs
FRC control system docs are scattered:
Don't be overwhelmed. Just take a breadth-first survey so you can go back when you need something, e.g. to learn how to wire and configure the cRIO, radio, and speed controllers.
For 2012, WPI provided a new framework for "command-based" robot programming and SmartDashboard features for viewing, changing, and graphing robot data values. See the 2012 WPILib Cookbook. This stuff is intended to make robot programs better organized and faster to iteratively develop. We didn't test them out yet since they didn't mesh with the FIT-PC and AOS library, but I really think they're worth trying.

To start programming in C++

Before the control kit and the robot kit arrive you can start learning about C++, the Eclipse-based development environment, and all about the control system.

C++ is a difficult and error-prone programing language. It's good to first learn about programming using a more modern and higher level language like Java, Python, or Ruby. But eventually you'll need to know C++ to program the FRC robot on Team 971. (Some other teams use Java or LabView.)

Before programming large, safety-critical robots, spend time learning C++ programming on a laptop where you can try things quickly and make full use of a screen and keyboard and debugger.

Here's one way to set up tools for C++ development.

  • Install Eclipse with the CDT (C Development Toolkit).
  • For cRIO programming, after you've learned C++, install the full Wind River Workbench from the installer DVDs.
  • If you're running on Windows, install Cygwin or MinGW/MSYS and its gcc, make, and gdb packages. (Linux generally comes with C++ compilers, so you get to skip these steps. On Macintosh, install Xcode to get a C++ compiler.)
    • Download Cygwin setup.exe (click the "Install or update now!" link on that page).
    • Run the installer program, "setup.exe", and go through the installation wizard: Pick a mirror site. Expand the "devel" section and pick "gcc", "gdb", and "make". Then start the download.
    • To enable the Wind River Workbench to find this compiler, you'll need to add this directory to the search 'Path' for executable programs. To do that, add the text
      • ;C:/cygwin/bin
    • to the end of your Path variable. The steps are:
      1. Go to Windows System Properties control panel > Advanced > Environment Variables > System Variables > "Path".
      2. Double-click on the Path variable to edit it.
      3. Append  ;C:/cygwin/bin   to the end of the Path value.
      4. "OK" all the way out of the control panel.
    • Restart Eclipse.
  • Find a book or an online tutorial on C++. Here are some examples that sound like a good fit. I have not read them so I can't review them.
  • Start working through your tutorial. Write some programs using the Eclipse editor and debugger.

Try creating a sample C++ project within Eclipse:
  1. File > New > Example... > Native Sample Project > The Complex Demonstration Program > Finish.
  2. Project > Build All.
  3. Look in the Build Console for build output. There should be no red build errors. Later when you start modifying the program, goofs will cause build errors to show up here.
  4. Double-click on main.cpp in the Project view to open the source code in an editor view. Read this source file to get an idea what this program does.
  5. The project also has files Complex.h and Complex.cpp in the "complexlib" folder, and iolib.h and iolib.cpp in the "iolib" folder. You can expand these folders and open these source files.
  6. Run the program using the Run icon in the toolbar. The program prints and reads text in the Console view, so look there. Exit the program.
  7. Run the program again using the Debug icon on the toolbar. You'll have to configure it the first time. In the Debug "Create, manage, and run configurations" dialog, pick C/C++ Local Application, click the "+ new launch configuration" button, configure the project name if needed, then click Debug. Eclipse will switch to the "Debug perspective", which is a different arrangement of views, suited to the job of debugging. This time the programs text input and output will go to a separate Console window.
  8. Tinker with the debugger. You can set breakpoints, step through the program, and examine & change variable values.
    • E.g. set a breakpoint on the line "char do_quit='n';" in main.cpp. Resume program execution until it gets to that step. (If it has trouble finding the source code for main.cpp, use the file dialog to show it where the file is, inside WindRiver/workspace/complex_Native.
    • In the Variables view, expand the info about variables a and b to see their member variables. Notice that these member variables contain garbage values. They have not been initialized. That's because the class Complex doesn't have any constructor code to initialize its member variables. In a minute we'll fix that.
  9. Let the program run to completion, or terminate it early using the red block icon on the toolbar.
  10. Try modifying the program.
  11. Switch back to the Application Development perspective.
  12. Add a constructor in Complex.h and Complex.cpp that initializes its re and im fields to 0.0.
  13. Debug the program again, and notice the properly initialized values a.re, a.im, b.re, and b.im. (If the debugger pauses at the beginning of main(), these values will not yet be initialized. Once it pauses at the breakpoint, they should be properly initialized.)

C++ Language

Focus on basic control structures, functions, classes, arrays, and pointers, also the built-in integer, float, and character data types.

C++ is loaded down with complicated features that you won't need. Try to avoid macros ('#DEFINE'), exceptions ('try' and 'throw'), operator overloading, templates, I/O streams, 'friend', name spaces, the 5 kinds of "cast", exceptions, and "placement new". Use 'new' instead of the old style 'malloc'. Use 'const' or 'enum' instead of the creaky old '#DEFINE' constants. Defer learning about namespaces and references.
In addition to all the tutorial books there are many "traps and pitfalls" books on C++. (My favorite title is Enough Rope to Shoot Yourself in the Foot: Rules for C and C++ Programming.) You'll want to know some of these tips.

Setting up Subversion for Source Code Control

A source code version control system enables coordination between multiple people working on a program or on the CAD drawings.

You can access Subversion using all of these tools:
Learning Subversion:
Here's a short introduction to Subversion at the Linux command line from a class at UCB. (Parts of it are specific to Linux and to that class.)

    The team's Subversion repository is now at https://robotics.mvla.net/svn/frc971/2012/trunk/src/
    The first step to do in Eclipse + Subclipse is to
    • Pick the Perspective "Subversion Repository Exploring"
    • Right-click in the "SVN Repositories" View
    • Add this repository.

     

    More information sources

    FIRST Robotics Challenge (FRC), Forums, and email broadcasts
    FRC 2009 Control System documents (including the Control System Manual and links for software updates) and technical specs
    FRC 2009 Competition Manuals and Team Updates
    FRC Software Updates, with links to the WPILib C++ docs
    WPI's FIRST Robotics Resoure Center (note: the programming section applies to the older 2008 controller)
    WPI's Think Tank portal
    Team 1114 docs, also see their "Simbot Prime, C++ beta test code" link to download their sample program in a .zip archive
    National Instruments NI cRIO-9074 real-time controller
    National Instruments tutorials on machine vision
    FIRST Robotics Challenge webcasts


    There are lots of docs in the FRC WindRiver Workbench installation. I copied the most interesting ones to the team's Subversion server, in trunk/docs/ and trunk/docs/FRC + National Instruments docs/. Also see the installation directories:

    • Workbench/FRC docs
      • C:\WindRiver\docs\extensions\FRC  -- esp. C Programming Guide for FRC, C++ Reference, FRC Vision API Specification
    • NI docs
      • C:\Program Files\National Instruments\CompactRIO\manuals  -- esp. crio-frc_Operating_Instructions.pdf
      • C:\Program Files\National Instruments\LabVIEW 8.5\manuals  -- esp. intro parts of FRC_Programming_Guide.pdf, PID_User_Manual.pdf
      • C:\Program Files\National Instruments\Vision\Documentation\Concepts_Manual.pdf
      • C:\Program Files\National Instruments\Vision Assistant 8.6\manuals\VA_Tutorial.pdf
    • VxWorks docs
      • C:\WindRiver\docs\extensions\eclipse\plugins\com.windriver.ide.doc.vxworks\vxworks_application_programmers_guide_6.3\vxworks_application_programmers_guide_6.3.pdf, e.g. task management



    Be aware that the Eclipse UI has different features with similar names like

    • New > Native Application Project vs. New > Example... -> Native Sample Project
    • Import... vs. adding a project from the SVN Repository Exploring perspective
    • Install into Eclipse... vs. Software Updates > Find and Install...
    • Project > Build Options vs. Project > Properties > Build Properties

     

    Definitions

    PID controller: A feedback loop for accurate motor control that adds Proportional, Integral, and Derivative components. See PID Controller on Wikipedia and the in-depth article from National Instruments, PID_User_Manual.pdf, mentioned above.

    embedded system: A computer embedded in a special purpose device such as a robot, CD player, MRI machine, or airplane. It's typically short on memory and has no keyboard, display, hard disk, speakers, etc.

    real-time software: Software that has to meet time deadlines, e.g. turn off the X-ray before over-exposing the patient, output the next audio-video data before there's a hiccup, or adjust a wing flap so the plane keeps flying. The timing must be predictable, not necessarily fast. Stopping at a debugger breakpoint will keep the program from meeting deadlines.

    hard real-time: Missing a deadline may be catastrophic, like crashing the airplane.

    soft real-time: Missing a deadline is ugly but recoverable, like glitchy video playback.