Cleaning Up – Preprocessor Directives
If you’ve taken a look at the previous program that blinks LEDs using the millis() function then you might have realized that things are beginning to get a bit complex. What if you wanted to change the delay interval or change the LED pins?
The delay interval appears in only one statement, so updating that is easy enough but the LED pins appear in multiple statements. It’s not uncommon to reference the same pins in multiple locations and it’s easy enough to forget to update all the references. Trust us, we’ve all done similar things before.
Thankfully, there’s a better way to structure your programs. The C programming language has something called pre-processor directives which are ideal for something like this. Pre-processor directives are nothing but statements that begin with “#define” and are commonly placed at the beginning of programs. They can be sued to equate meaningful words to things like pin numbers or time intervals.
Remember the “LED_BUILTIN” that we’ve used to reference the pin number for the built-in LED? It follows the same principle. It’s not only easier to use meaningful words, but they also prevent errors if used correctly by providing a single statement that can be updated as required.
Using pre-processor directives
Let’s re-write the non-blocking LED example with some directives.
We would need to define two directives – one for the external LED and one for the time interval as follows:
We update the setup() function to make use of these directives:
Lastly, we update the loop() function to make use of these directives:
And that’s it, let’s compile and run this example. Here is the result:
If we want to change the time interval then all we need to do is update the TIME_INTERVAL directive to a new value, say 100 and then compile/upload the program. Here is the result:
The complete Arduino project is available for download using the following link. Downloads are restricted to registered users. Registration is and will always be 100% FREE.
Project Source: P3_Cleaning_Up_Directives
This project uses standard Arduino libraries and is thus compatible with all Arduino boards that contain the built-in LED (on pin 13) and digital pin 0. Make sure the correct board is selected in the Arduino IDE.