Hi everyone, I'm new to Arduino programming and I'm a bit confused with the use of #define. Here's an example code I came across where it is used:
#define SENSOR_PIN A0
#define LED_PIN 13
void setup() {
pinMode(SENSOR_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
int sensorValue = analogRead(SENSOR_PIN);
if (sensorValue > 500) {
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
}
Could someone explain to me what it does here and why to use it? Why not use this instead:
int SENSOR_PIN A0 int LED_PIN 13
To put it simply, whenever the constant (SENSOR_PIN or LED_PIN) is called inside the program, the compiler replaces it with the defined constant value, i.e., A0 and 13, just like it does with global variables.
But unlike a variable, it assigns the value to all instances of the constant before the code is even compiled.
#define is a type of preprocessor directive, meaning the compiler preprocesses it before compiling the code, thus taking up zero memory. The constant here is called the macro name (SENSOR_PIN or LED_PIN), and the value is called the macro value.
The reasons it's a better approach than simply using variables are:
- They don't occupy any memory.
- They improve code readability.
- They can also be used with conditional directives (#ifdef, #ifndef, etc.) or functions to create code that behaves differently depending on certain conditions.
Hope this helps.
The #define preprocessor directive is a valuable tool in C++ and Arduino programming that enables programmers to assign meaningful names to constant values. These defined constants, often referred to as macros, are processed by the compiler before the code is executed.