Reference Language (extended) | Libraries | Comparison | Board
A variable is a way of naming and storing a value for later use by the program, such as data from a analog pin set to input. (See pinMode for more on setting pins to input or output.)
Before they are used, all variables have to be declared. Declaring a variable means 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.
Programmers should consider the size of the numbers they wish to store in choosing variable types. Also the specific place that variables are declared influences how the program will see the variable. This is called variable scope.
int inputVariable1; int inputVariable2 = 0; // both are correct
Once variables have been declared, they are used by setting the variable equal to the value one wishes to store with the assignment operator (single equal sign). The assignment operator tells the program to put whatever is on the right side of the equal sign into the variable on the left side.
inputVariable1 = 7; // sets the variable named inputVariable1 to 7 inputVariable2 = analogRead(2); // sets the variable named inputVariable2 to the // (digitized) input voltage read from analog pin #2
Once a variable has been set (assigned a value), you can test its value to see if it meets certain conditions, or you can use its value directly. For instance, the following code tests whether the inputVariable2 is less than 100, then sets a delay based on inputVariable2 which is a minimum of 100:
if (inputVariable2 < 100) { inputVariable2 = 100; } delay(inputVariable2);
This example shows all three useful operations with variables. It tests the variable ( if (inputVariable2 < 100)
), it sets the variable if it passes the test ( inputVariable2 = 100
), and it uses the value of the variable as an input to the delay() function ( delay(inputVariable2)
)
Style Note: You should give your variables descriptive names, so as to make your code more readable. Variable names like tiltSensor or pushButton help you (and anyone else reading your code) understand what the variable represents. Variable names like var or value, on the other hand, do little to make your code readable.
You can name a variable any word that is not already one of the keywords in Arduino. Avoid beginning variable names with numeral characters.
Corrections, suggestions, and new documentation should be posted to the Forum.
The text of the Arduino reference is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.