Difference between #define and int for blinking an

The example for blinking an LED in the "Getting started with Arduino" book by Massimo Banzi uses:

#define LED 13   //LED connected to digital pin 13

The example that came with the the IDE uses:

int ledPin = 13;      // LED connected to digital pin 13

Why did Massimo use #define and the IDE example use int? What I want to do is write a "for statement" that changes the pin assignment i.e.:

 for(i=5; i < 11; i++);  // applies power to pins 5 through 10
  {
  ledPin = i;                          // increments Pin by plus one (except first time around)    
  digitalWrite(ledPin, HIGH);   // sets ledPin to high
  delay(200);                        // delalys 200 ms  
  digitalWrite(ledPin, LOW);    // sets the ledPin off  
  }

Would it matter if I used:

#define ledPin 5

or

int ledPin = 5;

?. I get the I get the feeling I must use int to assign the pin vs. #define, is this correct?

Thanks for any help.

In most introductory sketches, for defining pin numbers, the two approaches are interchangeable.

#define FOO 4 is just a fancy way of setting up a "search and replace" in your code. Wherever "FOO" appears, the compiler pretends it saw a "4" instead. It can't be changed while the sketch is running, and it takes no memory in the processor.

int foo = 4; is a variable. It takes a little memory (two bytes) to store the value, and in fact it takes a little more memory to store the original value you started with. However, this allows the sketch to modify that variable under any desired circumstances, and thus use the new value from that time on.

1 Like

Thank you very much for the response, It answered my question. I really appreciate the help.

Judging by discussion on the developer's mailing list, you'll soon find the standard way of doing this in tutorials will probably change to:

const int ledPin = 13

--Phil.

Thanks for tip, I adjusted my post.

...

 for(i=5; i < 11; i++);  // applies power to pins 5 through 10

{
 ledPin = i;                          // increments Pin by plus one (except first time around)    
 digitalWrite(ledPin, HIGH);   // sets ledPin to high
 delay(200);                        // delalys 200 ms  
 digitalWrite(ledPin, LOW);    // sets the ledPin off  
 }




Would it matter if I used:



#define ledPin 5




or



int ledPin = 5;

Answer:

Yes it would matter.
Because the code ledPin = i; tries to assign a value to ledPin, this will not be possible when using either #define or const datatype.

You are best off using a byte :slight_smile:

And, you have an error in you for loop syntax: for(i=5; i < 11; i++); the ; should not be there. :slight_smile:

Thanks sooo much!!! I finally got the code working the way I wanted it! Just took me forever. Thanks a ton.