5.12. Arduino Coding Style GuideΒΆ

The sample code in this course is steadily evolving toward a consistent set of programming conventions chosen for clarity to novice programmers. The code is intended to serve both as a role model for good practice and as templates from which to copy usable fragments. The following notes are an evolving style guide for writing and updating the Arduino examples.

  1. File structure template
    1. Begin with a set of comments clearly describing the purpose and assumptions of the code.
    2. Import any required library headers.
    3. Define constants.
    4. Define global variables.
    5. Define setup() and loop().
    6. Define subroutines (functions).
  2. General conventions
    1. Use the loop() function as an event-loop, i.e., allow it to exit and be iterated, rather than capturing control within it.
    2. Invoke all one-time activity from setup(), possibly by calling subroutines.
    3. Keep functions short.
  3. C++ versus Arduino .ino
    1. Place setup() and loop() right after the global variables, even if they call subroutines; the Arduino IDE will re-order them during compilation to avoid forward reference errors. Note that this violates C++ convention by omitting the forward declaration, but is intended to make code more legible for novices by placing the standard entry points in a more visible location.
    2. Avoid preprocessor directives wherever possible.
    3. Avoid the ‘static’ storage class. Persistent variables and subroutine functions are declared as global even if they only actually need file extent. (This is generally considered poor C++ style; globals are usually discouraged.)
    4. Otherwise, wherever possible use a style which is valid for both the Arduino IDE and the more restrictive C++ rules. The Arduino IDE protects the user from a number of possible C++ errors, but using good C++ style will help avoid future traps.
  4. Variables and constants
    1. Names should suggest the purpose and function. E.g. use ‘pointing_servo’, not ‘servo1’, ‘my_servo’, or ‘servo’.
    2. Use variable names which suggest the available freedom of choice. I.e. a novice may need prompting that a variable can have any legal name, not just one of the conventional example forms (“switch_pin”, input_pin_1”, etc.).
    3. Constants should generally be all uppercase.
    4. Names should generally be longer than a single character.
    5. Specify units in the comments wherever relevant (e.g. microseconds, Volts).
    6. Local non-static variables are preferred to global variables wherever possible.
    7. Use const declarations instead of #define directives.
  5. Iteration constructs
    1. Stick to basic usage of iteration constructs. E.., for-loops should always include all three terms even though they are optional in C++.

Previous topic

5.11. SolidWorks Overview

Next topic

6. Reference Resources