Arduino for beginners : Define

WARNING: Preprocessor macros, although tempting, can produce quite unexpected results if not done right. Always keep in mind that macros are textual substitutions done to your source code before anything is compiled. The compiler does not know anything about the macros and never gets to see them. This can produce obscure errors, amongst other negative effects. Prefer to use language features, if there are equivalent (In example use const int or enum instead of #defined constants).

That said, there are cases, where macros are very useful (see the debug macro below for an example).

The #define directive is used to define values or macros that are used by the preprocessor to manipulate the program source code before it is compiled. Because preprocessor definitions are substituted before the compiler acts on the source code, any errors that are introduced by #define are difficult to trace.

By convention, values defined using #define are named in uppercase. Although doing so is not a requirement, it is considered very bad practice to do otherwise. This allows the values to be easily identified when reading the source code.

Today, #define is primarily used to handle compiler and platform differences. E.g., a define might hold a constant which is the appropriate error code for a system call. The use of #define should thus be limited unless absolutely necessary; typedef statements and constant variables can often perform the same functions more safely.

In the Arduino world you commonly see #define used when you are setting up I/O pins for sensors, LEDs and other tasks. Lets look at an example

[codesyntax lang=”cpp”]

void setup()
{
pinMode(11, OUTPUT); //set the LED pin as an output
pinMode(10, OUTPUT); //set the LED pin as an output
pinMode(9, OUTPUT); //set the LED pin as an output
}

[/codesyntax]

Then in the loop you may have

digitalWrite(11, HIGH); // red led off

The code above is perfectly valid and will work but the problem is that it’s not overly clear what these are used for and if you had numerous pins used it could quickly get confusing. Instead you could do the following

 

[codesyntax lang=”cpp”]

#define redled 11
#define blueled 10
#define greenled 9

void setup()
{
pinMode(redled, OUTPUT); //set the LED pin as an output
pinMode(blueled, OUTPUT); //set the LED pin as an output
pinMode(greenled, OUTPUT); //set the LED pin as an output
}

[/codesyntax]

 

Then in the loop you may have

digitalWrite(redled, HIGH); // red led off

That looks a lot better to me

This div height required for enabling the sticky sidebar
Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views :