Global vs.Local Variables

So far, we’ve declared variables inside a function block (inside the function’s curly braces), which means they are local variables.  Only the function declaring a local variable can see or modify it.  Also, a local variable only exists while the function that declares it is using it.  After that, it gets returned to unallocated memory so that another function (like loop) could use that memory for a different local variable.

If your sketch has to give more than one function access to a variable’s value, you can use global variables.  To make a variable global, just declare it outside of any function, preferably before the setup function.  Then, all functions in the sketch will be able to modify or retrieve its value.  The next example sketch declares global variables and assigns values to them from within a function.

Example Sketch – StoreRetrieveGlobal

This example sketch declares a, c, and root2 as global variables (instead of local).  Now that they are global, both the setup and loop functions can access them. 

  • Modify your sketch so that it matches the one below.
  • Save the file as StoreRetrieveGlobal, then upload it to the Arduino.
  • Open the Serial Monitor and verify that the correct values are displayed  repeatedly by the loop function.
// Robotics with the BOE Shield - StoreRetrieveGlobal

int a;
char c;
float root2;
    
void setup()
{
  Serial.begin(9600);

  a = 42;
  c = 'm';
  root2 = sqrt(2.0);
}

void loop()
{
  Serial.println(a);
  Serial.println(c);
  Serial.println(root2);
  delay(1000);
}

Your Turn – More Variable Types

There are lots more data types than just int, char, float, and byte

  • Open the Arduino Language Reference, and check out the Data Types list.
  • Follow the float link and learn more about this data type.
  • The long data type will be used in a later chapter; open both the long and int sections.  How are they similar? How are they different?