Why #define is used...
 
Notifications
Clear all

Why #define is used in Arduino programming?

3 Posts
4 Users
1 Reactions
3,415 Views
0
Topic starter

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

nathan 09/05/2024 11:44 am

@tech-geek You can also use "const int SENSOR_PIN A0"


2 Answers
1

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:

  1. They don't occupy any memory.
  2. They improve code readability.
  3. 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.


0

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.


Share: