A variable is used in programming to store a value that may change during the life of the Arduino sketch. Memory is set aside for storing the variable and the variable is given a name which allows it to be accessed in the sketch.
These are the few variables that are used frequently in Arduino sketches:
The standard form of variable definition is:
Variable_Datatype can be int or float depending on the type of variable you are want. Variable_Name is the name of variable. Variable is referenced or used by its name in the program.
By giving the variable a type and name, space is made available in memory for this variable.
Example: if I want to count the number of times main loop have been executed, I have to first define the variable count by:
Variables can be given any name that you like, so long as it sticks to the rules set out below. It is best to give variables meaningful names that help you and others to understand the sketch better.
A variable can be assigned a value by the following form:
Variable_Name = Expression;
Expression will give a valid number that will be assigned to the variable. Let us count how many time loop has been executed. Following is the Arduino sketch:
Let us make a new sketch, where you will add two float variable to a new variable. Given below is the code:
When the value of the variable is sent to the serial monitor window, we can see that println() automatically rounds the number off to two decimal places.
The second time that println() is used to send the value of the variable to the serial monitor window, the number of decimal places is specified as 5. This is done by passing a second parameter value of 5 to the println() function.