Variables in Arduino:

  • Arduino supports almost all the variables types that exist in C language.
  • Variables may be used in the Arduino to access any of its pin, that may be Digital or Analog Pin.

Variables Types:

  • char
  • byte
  • int
  • unsigned int
  • long
  • unsigned long
  • float double

Declaring Variables:

  • Before variables can be used in program, all variables need to be declared.
  • Declaring a variable refers to defining its type, and optionally, setting an initial value (initializing the variable). Variables do not have to be initialized (assigned a value) when they are declared, but it is often useful.
int x;       // variable 'x' declared of 'int' type
int y = 7;  // variable 'y' declared of 'int' type and intialised (assigned) value of '7'
x = 5;     // variable x intialised value of 5

Variable Scope:

Variables that are used in Arduino from C programming language, have a property called scope.

A scope in programming language is a region of the program where a defined variable can have it;s existence and beyond that variable can be accessed.

There are usually three places where variables can be declared:

  1. Inside a function or a block, called local variable.
  2. Outside of all functions, called global variable.
  3. In the definition of function parameters, called formal parameters.
Local Variable:
  • These variables are declared inside a function or block of code.
  • It can be accessed only by the statements that are inside the same function or block of code.
  • Local variables doesn't have existence outside the function.
void loop() {
  int x = 5;  // local variable declaration, 'x' can be accesses only with loop() function
}
Global Variable:
  • A global variable can be accessed by any function in the program.
  • It is usually declared at the top of the program.
  • Global variable is available for use throughout the entire program after its declaration.
int y = 3; // global variable that can be accessed throughout the program

void setup() {
  // 'y' can be accessed here
  // 'x' can't be accessed here
}
void loop() {
  // 'y' can be accesses here
  int x = 5;  // local variable declaration, 'x' can be accesses only with loop() function
}