Arduino.ru
Переменная – это место хранения данных. Она имеет имя, значение и тип. Например, данное объявление (называется декларацией):
int pin = 13;
создает переменную с именем pin , значением 13 и типом int . Затем в программе имеется возможность обратиться к данной переменной через имя с целью работы с ее значением. Например, в утверждении:
pinMode(pin, OUTPUT);
имеется значение вывода (13), которое будет передаваться в функцию pinMode(). В данном случае нет необходимости использовать переменную. Утверждение может работать и в таком виде:
pinMode(13, OUTPUT);
Преимущество переменной заключается в том, что необходимо определить значение вывода однажды и потом использовать его многократно. В последствии при изменении вывода 13 на 12 достаточно будет поменять только одну строку в программном коде. Также можно использовать специальные имена для подчеркивания значения переменной (напр., программа, управляющая светодиодом RGB, может содержать переменные redPin, greenPin и bluePin).
Переменные имеют другие преимущества перед такими значениями как число. Имеется возможность изменить значение переменной, используя присвоение. Например:
pin = 12;
изменит значение переменной на число 12. В данном примере не определяется тип переменной, т.к. он не меняется операцией присвоения. Имя переменной постоянно связано с типом, меняется только значение. [1] Перед присвоением значения необходимо декларировать переменную. Присвоение значения переменной без ее декларации вызовет следующее сообщение: error: pin was not declared in this scope».
При присвоении одной переменной другой происходит копирование значения первой переменной во вторую. Изменение значение одной переменной не влияет на другую. Например, после записи:
int pin = 13; int pin2 = pin; pin = 12;
только pin имеет значение 12, а pin2 еще равен 13.
Что означает слово «scope» в сообщение об ошибке, приведенной выше? Оно относится к части программы, в которой переменная может использоваться — областе видимости. Область видимости определяется местом ее декларации. Например, имеется возможность использовать переменную во всей программе, если задекларировать ее в начале программного кода. Такие переменные называются глобальными. Например:
int pin = 13; void setup() < pinMode(pin, OUTPUT); >void loop()
Из примера видно, что pin используется в обеих функциях setup() и loop(). Обе функции ссылаются на одну переменную, таким образом, изменение ее значения в одной функции повлияет на значение в другой:
int pin = 13; void setup() < pin = 12; pinMode(pin, OUTPUT); >void loop()
Функции digitalWrite(), вызываемой из loop(), будет передано значение 12, т.к. оно было присвоено переменной в функции setup().
Если переменная используется только один раз в функции, то ее декларируют в данной части программного кода, ограниченной скобками функции. Например:
void setup()
В данном примере переменная может использоваться только внутри функции setup(). При написании данного кода:
void loop() < digitalWrite(pin, LOW); // wrong: pin is not in scope here. >
будет выведено сообщение: «error: ‘pin’ was not declared in this scope». Данное сообщение будет выводиться, даже если вы задекларировали переменную где-то в программе, но пытаетесь ее использовать вне области видимости.
Почему не сделать все переменные глобальными? Если неизвестно где будет еще использоваться переменная, то почему ее надо ограничивать одной функцией? Когда переменная ограничена легче найти источник ее изменения. Если переменная глобальная, то ее значение может быть изменено в любом месте программного кода, что означает необходимость проследить ее изменение по всей программе. Например, когда переменная имеет некорректное значение, то гораздо легче найти причину если область видимости ограничена.
[1] В некоторых языках программирования, как Python, типы ассоциируются со значениями, а не с именами переменных. Таким образом, имеется возможность присвоит значение любого типа переменной. Это называется динамической типизацией.
Arduino.ru
Тип данных int (от англ. integer — целое число) один их наиболее часто используемых типов данных для хранения чисел. int занимает 2 байта памяти, и может хранить числа от -32 768 до 32 767 (от -2^15 до 2^15-1)
Для размещения отрицательных значений int использует, так называемый, дополнительный код представления числа. Старший бит указывает на отрицательный знак числа, остальные биты инвертируются с добавлением 1.
Arduino компилятор сам заботиться о размещение в памяти и представление отрицательных чисел, поэтому арифметические действия над целыми числами производятся как обычно.
Пример
int ledPin = 13;
Синтаксис
- var — имя переменной;
- val — значение присваиваемое переменной;
Замечание по использованию типа int
Когда переменная типа int в следствие арифметической операции достигает своего максимального значения, она «перескакивает» на самое минимальное значение и наоборот:
int x x = -32,768; x = x - 1; // x теперь равно 32,767 - перескакивает на минимальное значение x = 32,767; x = x + 1; // x теперь равно -32,768
Variables
A variable is a place to store a piece of data. It has a name, a value, and a type. For example, this statement (called a declaration):
creates a variable whose name is pin , whose value is 13 , and whose type is int . Later on in the program, you can refer to this variable by its name, at which point its value will be looked up and used. For example, in this statement:
it is the value of pin (13) that will be passed to the pinMode() function. In this case, you don’t actually need to use a variable, this statement would work just as well:
The advantage of a variable in this case is that you only need to specify the actual number of the pin once, but you can use it lots of times. So if you later decide to change from pin 13 to pin 12, you only need to change one spot in the code. Also, you can use a descriptive name to make the significance of the variable clear (e.g. a program controlling an RGB LED might have variables called redPin, greenPin, and bluePin).
A variable has other advantages over a value like a number. Most importantly, you can change the value of a variable using an assignment (indicated by an equals sign). For example:
will change the value of the variable to 12. Notice that we don’t specify the type of the variable: it’s not changed by the assignment. That is, the name of the variable is permanently associated with a type; only its value changes. [1] Note that you have to declare a variable before you can assign a value to it. If you include the preceding statement in a program without the first statement above, you’ll get a message like: «error: pin was not declared in this scope».
When you assign one variable to another, you’re making a copy of its value and storing that copy in the location in memory associated with the other variable. Changing one has no effect on the other. For example, after:
int pin = 13; int pin2 = pin; pin = 12;
only pin has the value 12; pin2 is still 13.
Now what, you might be wondering, did the word «scope» in that error message above mean? It refers to the part of your program in which the variable can be used. This is determined by where you declare it. For example, if you want to be able to use a variable anywhere in your program, you can declare at the top of your code. This is called a global variable; here’s an example:
int pin = 13; void setup() pinMode(pin, OUTPUT); > void loop() digitalWrite(pin, HIGH); >
As you can see, pin is used in both the setup() and loop() functions. Both functions are referring to the same variable, so that changing it one will affect the value it has in the other, as in:
int pin = 13; void setup() pin = 12; pinMode(pin, OUTPUT); > void loop() digitalWrite(pin, HIGH); >
Here, the digitalWrite() function called from loop() will be passed a value of 12, since that’s the value that was assigned to the variable in the setup() function.
If you only need to use a variable in a single function, you can declare it there, in which case its scope will be limited to that function. For example:
void setup() int pin = 13; pinMode(pin, OUTPUT); digitalWrite(pin, HIGH); >
In this case, the variable pin can only be used inside the setup() function. If you try to do something like this:
void loop() digitalWrite(pin, LOW); // wrong: pin is not in scope here. >
you’ll get the same message as before: «error: ‘pin’ was not declared in this scope». That is, even though you’ve declared pin somewhere in your program, you’re trying to use it somewhere outside its scope.
Why, you might be wondering, wouldn’t you make all your variables global? After all, if I don’t know where I might need a variable, why should I limit its scope to just one function? The answer is that it can make it easier to figure out what happens to it. If a variable is global, its value could be changed anywhere in the code, meaning that you need to understand the whole program to know what will happen to the variable. For example, if your variable has a value you didn’t expect, it can be much easier to figure out where the value came from if the variable has a limited scope.
[block scope][size of variables]
[1] In some languages, like Python, types are associated with values, not variable names, and you can assign values of any type to a variable. This is referred to as dynamic typing.
Using Variables in Sketches
What are variables, and how can we use them in a sketch.
Last revision 01/24/2024
A variable is a place to store a piece of data. It has a name, a value, and a type. For example, this statement (called a declaration):
int pin = 13;
creates a variable whose name is
whose value is
and whose type is
Later on in the program, you can refer to this variable by its name, at which point its value will be looked up and used. For example, in this statement:
pinMode(pin, OUTPUT);
it is the value of pin (13) that will be passed to the pinMode() function. In this case, you don’t actually need to use a variable, this statement would work just as well:
pinMode(13, OUTPUT);
The advantage of a variable in this case is that you only need to specify the actual number of the pin once, but you can use it lots of times. So if you later decide to change from pin 13 to pin 12, you only need to change one spot in the code. Also, you can use a descriptive name to make the significance of the variable clear (e.g. a program controlling an RGB LED might have variables called redPin, greenPin, and bluePin).
A variable has other advantages over a value like a number. Most importantly, you can change the value of a variable using an assignment (indicated by an equals sign). For example:
pin = 12;
will change the value of the variable to 12. Notice that we don’t specify the type of the variable: it’s not changed by the assignment. That is, the name of the variable is permanently associated with a type; only its value changes. [1] Note that you have to declare a variable before you can assign a value to it. If you include the preceding statement in a program without the first statement above, you’ll get a message like: «error: pin was not declared in this scope».
When you assign one variable to another, you’re making a copy of its value and storing that copy in the location in memory associated with the other variable. Changing one has no effect on the other. For example, after:
1int pin = 13; 2 int pin2 = pin; 3pin = 12;
only pin has the value 12; pin2 is still 13.
Now what, you might be wondering, did the word «scope» in that error message above mean? It refers to the part of your program in which the variable can be used. This is determined by where you declare it. For example, if you want to be able to use a variable anywhere in your program, you can declare at the top of your code. This is called a global variable; here’s an example:
1int pin = 13; 2 void setup() 3 4 pinMode(pin, OUTPUT); 5 > 6 void loop() 7 8 digitalWrite(pin, HIGH); 9 >
is used in both the setup() and loop() functions. Both functions are referring to the same variable, so that changing it one will affect the value it has in the other, as in:
1int pin = 13; 2 void setup() 3 4pin = 12; 5 pinMode(pin, OUTPUT); 6 > 7 void loop() 8 9 digitalWrite(pin, HIGH); 10 >
Here, the digitalWrite() function called from loop() will be passed a value of 12, since that’s the value that was assigned to the variable in the setup() function.
If you only need to use a variable in a single function, you can declare it there, in which case its scope will be limited to that function. For example:
1void setup() 2 3 int pin = 13; 4 pinMode(pin, OUTPUT); 5 digitalWrite(pin, HIGH); 6 >
In this case, the variable pin can only be used inside the setup() function. If you try to do something like this:
1void loop() 2 3 digitalWrite(pin, LOW); // wrong: pin is not in scope here. 4 >
you’ll get the same message as before: «error: ‘pin’ was not declared in this scope». That is, even though you’ve declared pin somewhere in your program, you’re trying to use it somewhere outside its scope.
Why, you might be wondering, wouldn’t you make all your variables global? After all, if I don’t know where I might need a variable, why should I limit its scope to just one function? The answer is that it can make it easier to figure out what happens to it. If a variable is global, its value could be changed anywhere in the code, meaning that you need to understand the whole program to know what will happen to the variable. For example, if your variable has a value you didn’t expect, it can be much easier to figure out where the value came from if the variable has a limited scope.
[block scope][size of variables]
[1] In some languages, like Python®, types are associated with values, not variable names, and you can assign values of any type to a variable. This is referred to as dynamic typing.
Suggested changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. You can read more on how to contribute in the contribution policy.
Need support?
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.