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.
- File structure template
- Begin with a set of comments clearly describing the purpose and assumptions of the code.
- Import any required library headers.
- Define constants.
- Define global variables.
- Define setup() and loop().
- Define subroutines (functions).
- General conventions
- Use the loop() function as an event-loop, i.e., allow it to exit and be iterated, rather than capturing control within it.
- Invoke all one-time activity from setup(), possibly by calling subroutines.
- Keep functions short.
- C++ versus Arduino .ino
- 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.
- Avoid preprocessor directives wherever possible.
- 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.)
- 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.
- Variables and constants
- Names should suggest the purpose and function. E.g. use ‘pointing_servo’, not ‘servo1’, ‘my_servo’, or ‘servo’.
- 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.).
- Constants should generally be all uppercase.
- Names should generally be longer than a single character.
- Specify units in the comments wherever relevant (e.g. microseconds, Volts).
- Local non-static variables are preferred to global variables wherever possible.
- Use const declarations instead of #define directives.
- Iteration constructs
- Stick to basic usage of iteration constructs. E.., for-loops should always include all three terms even though they are optional in C++.