db2db
1
Some things seem to be ok to place in setup(), or can be put in the lines above setup().
Is there any benefit one way or another?
void setup()
{
int buttonPin = 3;
pinMode(buttonPin, INPUT);
}
** or **
int buttonPin = 3;
void setup()
{
pinMode(buttonPin, INPUT);
}
db2db:
Some things seem to be ok to place in setup(), or can be put in the lines above setup().
Is there any benefit one way or another?
void setup()
{
int buttonPin = 3;
pinMode(buttonPin, INPUT);
}
** or **
int buttonPin = 3;
void setup()
{
pinMode(buttonPin, INPUT);
}
this one creates a LOCAL variable in setup()
void setup()
{
int buttonPin = 3;
pinMode(buttonPin, INPUT);
}
this one creates a GLOBAL variable which can be used within setup or any other function:
int buttonPin = 3;
void setup()
{
pinMode(buttonPin, INPUT);
}
google variable scope
1 Like
db2db
3
Ah yes, scope. Of course.
Thanks very much.
The advantage of a global varaible is that you probably are going to use digitalRead/Write in the loop and then you can use the same variable.
As the value of the var is always between 0..255 and constant you better declare it as
const uint8_t buttonPin = 3;
that give the compiler the most information about how the variable is used.
The compiler can then optimize it much better.