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.)
You set a variable by making it equal to the value you want to store. The following code declares a variable inputVariable, and then sets it equal to the value at analog pin #2:
int inputVariable = 0; # Declares the variable; this only needs to be done once inputVariable = analogRead(2); # Set the variable to the input of analog pin #2
inputVariable is the variable itself. The first line declares that it will contain an int (short for integer.) The second line sets inputVariable to the value at analog pin #2. This makes the value of pin #2 accessible elsewhere in the code.
Once a variable has been set (or re-set), you can test its value to see if it meets certain conditions, or you can use it's value directly. For instance, the following code tests whether the inputVariable is less than 100, then sets a delay based on inputVariable which is a minimum of 100:
if (inputVariable < 100) { inputVariable = 100 } delay(inputVariable)
This example shows all three useful operations with variables. It tests the variable ( if (inputVariable < 100)
), it sets the variable if it passes the test ( inputVariable = 100
), and it uses the value of the variable as an input to the delay() function ( delay(inputVariable)
)
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.
All variables have to be declared before they are used. Declaring a variable means defining its type, and setting an initial value. In the above example, the statement
int inputVariable = 0;
declares that inputVariable is an int, and that its initial value is zero.
Possible types for variables are: