Arduino Basic Tutorial

Variable in arduino programming

Variables in Arduino:

Variable in Arduino- In this article, I am going to explain to you variables and their types in very detail. I will explain the below example in my entire article.

Example1: variables in Arduino programming:


variable in arduino

The first line of the sketch in Example1 consists of declaring a variable global of type “int” called “myvariable”, and initializing it with the value of 555.

Let’s explain all this.

A variable in Arduino is an element of our sketch that acts as a small ” Drawer ” (identified by a name chosen by us) that keeps a certain content. That content (what is called the value of the variable) is can be modified at any time during the execution of the sketch: hence the name of “variable”. The importance of variables in Arduino is immense, since all the sketches they make use of them to host the values ​​they need to function.

The value of a variable in Arduino can be obtained in various ways: it can have been assigned literally (like the one in Example1, were just starting we explicitly assign the variable called “myvariable” the value 555), but It can also be the data obtained by a sensor, or the result of a calculation, etc. No matter where it comes from initially, that value can always be changed at any time after the execution of the sketch, if we so desire.

Declaration and initialization of a variable in Arduino:

Before we can start using any variable in our sketch; However, we must first create it. When creating a variable it is usually called “declare a variable”. In the Arduino language, when you declare a variable is also essential to specify its type. The type of variable is we will choose according to the type of data (integers, decimal numbers, a string of characters, etc.) that we want to store in that variable in Arduino. That is: each variable in Arduino can only save values ​​of a certain type, so we must decide in its declaration which type of variable is the one that interests us the most according to the type of data that we plan to store. Assign a value to a variable that is of a type other than the one provided for this causes a sketch error.

The possible types of the Arduino language will be detailed in the paragraphs following, but you can already know that the general syntax of a declaration is always a line written like this: typeVariable variableName ;. In the specific case of wanting to declare several variables of the same type, instead of writing one declaration separately for each of them, it is possible to declare them all on the same line, generically like this:

General  syntax of declaring a variable in Arduino:

Optionally, at the same time that the variable is declared, an initial value: is called “initializing a variable”. Initialize a variable when it is declared it is not mandatory, but it is highly recommended. In Example1, We declare the variable called “myvariable” of type “int” (which is a data type among the various existing ones designed to store whole numbers), and also, We also initialize it with the initial value of 555. From there it can already be deduced that the general syntax of initialization is always a line written like this:

general syntax of initialization of a variable in Arduino:

One might wonder why it is convenient to use initialized variables instead of writing its value directly where it is needed. For example, in the case of the code of Example1, we have assigned the value of 555 to “myvariable” when we could have written it directly inside the instruction Serial.println() like this: Serial.println(555) ;. The main reason is that working with variables makes it much easier for us to understand and maintain our programs: if that value appears written in many different lines of our code and has to be changed, using a variable initialized with that value as we should only change the initialization of the variable and automatically all the times where that variable appears within our code it would have this new value; if we directly wrote that value on each line, we would have to go to it modifying line by line, with the consequent loss of time and the possibility of to make mistakes.

On the other hand, when declaring variables in Arduino, it is recommended to give our variables descriptive names to make the code of our sketch more readable. For example, names like “sensorDistance” or “buttonOn” will help to better understand what those variables represent. To name a variable in Arduino, You can use any word we want, as long as it is not already an Arduino language reserved word (such as the name of instruction, etc.) and that does not start with a digit.

Assigning values ​​to a variable in Arduino:

default (usually of no interest to us) until a value is assigned differently at some point during the execution of our sketch. The general syntax to assign a new value to a variable in Arduino (either because it has not been initialized, or especially because you want to overwrite a previous value with a new one), it is:

For example, if the variable is called “myvariable” and is of type integer, you could be written inside some section of our sketch a line such as myvariable = 567;

to assign the new numeric value of 567. Important note that the assignment line reads “from left to right”: the value “NewValue” is assigned to the variable “variableName”.

The assignments of values ​​to variables can be very varied: not always they are direct values ​​as in Example1. A fairly common case is to assign to a variable a value that depends on the value of another. For example, if we assume that we have a variable called “y” and another called “x”, we could write the following:

 The previous sentence should be read like this: whatever value it has currently the variable “x” is added 10 and the result is assigned to the variable “y” (is that is, if for example “x” has a value of 5, “y” will have a value of 15).

We can even find assignments of the type y = y + 1; (as in fact it happens with the sketch of Example1). The key here is to understand that the symbol “=” is not that of mathematical equality it is assignment. Therefore, what a line like the previous one does is add a unit to the current value of the variable “y” (it is understood that it is of numeric type) for then assign this new resulting value again to the variable “y”, overwriting the one you had previously. That is, if initially “y” is worth 45 (for example), after the assignment y = y + 1 is executed; will be worth 46.

Scope of a variable in Arduino:

Another important concept in relation to variables is the scope of a variable. In this sense, a variable can be “global” or “local”.

global  variable  in Arduino

For a variable to be global, it must be declared at the beginning of our sketch; that is, before (and outside) the “void setup()” and “void loop() ”. In fact, when talking about the structure of a sketch we had already mentioned the existence of this section of variable declarations global. A global variable in Arduino is one that can be used and manipulated from any point of the sketch. That is, all the instructions of our program regardless of what section they are written in (“void setup()”, “Void loop()” or others that may exist) can consult and also change the value of that variable in Arduino.

Local variable in Arduino

For a variable to be local, it must be declared inside one of the sections of our sketch (that is, inside “void setup()” or “void loop() ”or others that may exist). A local variable in Arduino is one that only can be used and manipulated by the instructions written within the same section where it has been declared. This type of variable is useful is long and complex skits to ensure that only one section has access to its own variables, as this avoids possible errors when a section inadvertently modifies variables used by another section.

types of a variable in Arduino:

The types of variables that the Arduino language supports are:

Boolean type:

The variables of this type can only have two values: true or false. They are used to store a state between those two possible, and thus make the sketch react depending on whether it detects one or the other in them. For example, Boolean variables can be used to check whether have received data from a sensor (true) or not (false), to check if any actuator is available (true) or not (false), to check if the value of another different variable fulfills a certain condition such as that of being greater than a specific number (true) or not (false). The value stored in a Boolean variable in Arduino always occupies one byte of memory.

To explicitly assign a variable of type “boolean” the value of true, you can use the special word “true” (without quotes) or the value “1” (without quotation marks), and to assign the value false you can use the special word “false” (without quotes) or the value “0” (without quotes). That is, if in our sketch of For example, the variable “myvariable” would have been of type “boolean” instead of “int”, to assign the value of “true” we should have written a line similar to Boolean


(actually, a variable Boolean with any value other than 0 is already interpreted as having a value true: it doesn’t have to be the value 1 specifically).

Char type:

the value that a variable of this type can have is always a single character (a letter, a digit, a punctuation mark …). If what we want is to store a string of characters (that is, a word or a phrase) the type “char” does not serve us, we must use another type explained subsequently.

To explicitly assign a variable of type “char” a certain value (that is, a character), we must be careful to write that character in single quotes. Therefore, if in the sketch of Example1 the variable “Myvariable” would have been of type “char” instead of “int”, to assign the value of the letter A we should have written a line similar to char myvariable = ‘A’ ;.

Actually, characters are stored internally as numbers since electronic devices are unable to work with “letters” directly: They must always “translate” into numbers first so that they can then be stored and process. To find out which internal number a certain character corresponds to, and vice versa, the Arduino board uses the so-called ASCII table, which is a simple list of equivalences that associate each character with a specific number.

The fact that the characters for the Arduino board are actually recognized as numbers allows arithmetic operations to be performed with those characters (or rather, with their corresponding numeric value within ASCII table). For example: if we perform the operation ‘A’ + 1 we would obtain the value 66, since in the ASCII table the numeric value of the character ‘A’ is 65. In fact, even We could initialize a “char” variable by assigning it a numeric value instead of the corresponding character (that is: the line char myvariable = ‘A’; we could write as char myvariable = 65; both would be equivalent).

Each character variable in Arduino occupies 8 bits (one byte) of memory to store its value. This implies that there are 28 = 256 different possible values ​​for such a variable (it’s easy to see this if you count the combinations of 0s and 1s that can be obtained with 8 positions). As the values ​​of type “char” in actually number, the values ​​that a variable of this type can store They are within a range from -128 to 127.

Byte type:

The “byte” type: the value that a variable of this type can have is always an integer between 0 and 255. Like the variables of type “char”, the of type “byte” use a byte (8 bits) to store their value and, therefore, have the same number of different possible number combinations (256).

 int type:

The type “int”: the value that a variable of this type can have is an integer between -32768 (-215) and 32767 (215-1), because they use 2 bytes (16 bits) of memory to be stored. This is so for all Arduino boards except for the Due: in this board model the type “int” uses 4 bytes, and therefore, its value can be within a larger range, specifically between -2,147,483,648 (-231) and 2,147,483,647 (231 -1).

word type:

The “word” type: the “word” type variables on the Arduino board occupy 4 bytes to store its value. Therefore, they have the same number of possible numerical combinations different than the “int” variables, but Unlike these, the values ​​of a “word” variable cannot be negatives. On boards based on AVR-type microcontrollers, the same occurs same: variables of type “int” and “word” occupy the same space of memory (although in this case, however, it is only 2 bytes) but the values ​​of the latter cannot be negative. It is easy to see that the value that you can have a “word” variable on all boards except the Arduino is an integer between 0 and 65535 (216-1).

 short type:

The type “short”: the value that a variable of this type can have for all board models (whether based on AVR-type microcontrollers –the majority– or ARM type –la Due–) is an integer between -32768 (-215) and 32767 (215-1), because they use 2 bytes (16 bits) of memory to be stored. In this sense, the types “short” and “int” for plates of the AVR family are equivalent, but for the Arduino Due board the type “short” it is the only one that uses 16 bits.

Long type:

The “long” type: the value that a variable of this type can have for all board models (whether based on AVR-type microcontrollers or of type ARM) is an integer between -2,147,483,648 and 2,147,483,647 thanks to the fact that they use 4 bytes (32 bits) of memory to be stored. In this sense, the types “long” and “int” for boards of the ARM family are equivalents.

unsigned long type:

The “unsigned long” type: the value that a variable of this type can have for all board models (whether based on microcontrollers of type AVR or ARM) is an integer between 0 and 4,294,967,295 (232-1). To the like the variables of type “long”, those of type “unsigned long” use 4 bytes (32 bits) to store their value, and therefore have the same number of different possible numerical combinations (232), but unlike those, the values ​​of an “unsigned long” variable cannot be negative (as its own name already indicates). In this sense, the types “unsigned long ”and“ word ”for ARM family boards are equivalent.

float type:

The “float” type: the value that a variable of this type can have is a decimal number. Possible “float” values ​​can range from the number -3.4028235 · 1038 to the number 3.4028235 · 1038. Due to its great range of possible values, decimal numbers are used frequently to approximate continuous analog values. Nevertheless, they only have 6 or 7 digits in total precision. That is, the “float” values ​​do not are accurate, and may produce unexpected results, such as that, 6.0 / 3.0 does not exactly give 2.0.

Double type:

The type “double”: It is a synonym exactly equivalent to the type “float”, and therefore it does not provide any increase in precision with respect to this (at Unlike what happens in other languages, where “double” does provide the double precision). Both a variable of type “double” and one of type “Float” occupies four bytes of memory.

array type:

The “array” type: this data type does not actually exist as such. What there are arrays of variables of type “boolean”, arrays of variables of type “Int”, arrays of variables of type “float”, etc. In short: arrays of variables of any type of those mentioned so far. An array (also called “vector”) is a collection of variables of a specific type that all have the same and unique name but can be distinguished from each other by a number as an index. That is to say: instead of having different variables – for example of type “char” – each one independent of the others (varChar1, varChar2, varChar3 …) we can have a single array that group them all under the same name (for example, varChar), and allow that each variable can be manipulated separately thanks to the fact that within the array each is identified by a numeric index, written between square brackets (varChar [0], varChar [1], varChar [2] …). Arrays are used to win clarity and simplicity in the code, in addition to facilitating programming.

We can create –declare– an array (either in the declaration area global or within a specific section), in the following ways:

int varInt [6]; Declare an array of 6 elements (that is, individual variables) without initializing any.

int varInt [] = {2,5,6,7}; Declare an array without specifying the number of elements. However, they are assigned (between braces, separated by commas) the values directly to individual elements, for what the compiler is able to deduce the total number of elements in the array (in the example on the right, four).

int varInt [8] = {2,5,6,7}; Declare an array of 8 elements and initialize some of them (the first four), leaving the rest uninitialized. Logically, if initialize more elements than what allows the size of the array (for example, if assign 9 values ​​to an 8-element array), an error would occur.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button