Tutorial.Variables History

Hide minor edits - Show changes to markup

June 05, 2010, at 01:01 PM by Equipo Traduccion -
Changed line 90 from:

[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.

to:

[1] En algunos lenguages de programación, como Python, los tipos se asocian con valores, no a los nombres de variables, y se pueden asignar valores de cualquier tipo a una variable. Esto se conoce como tipos dinámicos (dynamic typing).

June 05, 2010, at 12:59 PM by Equipo Traduccion -
Changed lines 75-76 from:

En este caso, la variable pin sólo podrá ser usado dentro de la función setup(). Si tratas de hacer algo como esto:

to:

En este caso, la variable pin sólo podrá ser usada dentro de la función setup(). Si tratas de hacer algo como esto:

Changed lines 85-86 from:

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.

to:

Te puedes preguntar ¿por qué no hacemos todas las variables globales? Después de todo, si no sé dónde puedo necesitar una variable, ¿por qué limitar su alcance a una sola función? La respuesta puede que sea más fácil de averiguar lo que te parece. Si una variable es global, su valor podría cambiarse en cualquier parte del código, lo que significa que necesita entender la totalidad del programa para saber qué va a pasar con la variable. Por ejemplo, si la variable tiene un valor que no esperabas, puede ser mucho más fácil de averiguar de donde viene el valor si la variable tiene un alcance limitado.

June 05, 2010, at 12:54 PM by Equipo Traduccion -
Changed lines 83-84 from:

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.

to:

obtendrás el mismo mensaje que antes: "error: 'pin' was not declared in this scope" ("error: 'pin' no se declaró en este ámbito"). Es decir, a pesar de que has declarado pin en algún sitio en tu programa, está tratando de utilizarlo en alguna parte fuera de su ámbito de aplicación.

June 05, 2010, at 12:52 PM by Equipo Traduccion -
Changed lines 63-66 from:

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:

to:

Aquí, a la función digitalWrite() llamada desde loop() se le pasa el valor 12, ya que es el valor que se le asigna a la variable en la función setup().

Si tienes que utilizar una variable en una sola función, puedes declararla en la misma, en cuyo caso el ámbito (scope) de utilización se limita a esa función. Por ejemplo:

Changed lines 75-76 from:

In this case, the variable pin can only be used inside the setup() function. If you try to do something like this:

to:

En este caso, la variable pin sólo podrá ser usado dentro de la función setup(). Si tratas de hacer algo como esto:

Changed line 80 from:
  digitalWrite(pin, LOW); // wrong: pin is not in scope here.
to:
  digitalWrite(pin, LOW); // incorrecto: pin no tiene ámbito aquí.
June 05, 2010, at 12:44 PM by Equipo Traduccion -
Changed lines 47-48 from:

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:

to:

Como puedes ver, pin se usa tanto en la función setup() como en loop(). Ambas funciones hacen referencia a la misma variable, por lo que un cambio en una afectará al valor que tendrá en la otra, como en:

June 05, 2010, at 12:40 PM by Equipo Traduccion -
Changed lines 32-33 from:

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:

to:

Y ahora qué, puede que te preguntes ¿que significa la palabra "scope" (alcance) en ese mensaje de error anterior? Se refiere a la parte de tu programa en el que se puede usar la variable. Esto se determina por el lugar donde se declara. Por ejemplo, si quieres poder utilizar una variable en cualquier parte de tu programa, puedes declararla en la parte superior de tu código. Esto se llama variable global, aquí tienes un ejemplo:

June 05, 2010, at 12:34 PM by Equipo Traduccion -
Changed lines 23-24 from:

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:

to:

Cuando se asigna una variable a otra, estás haciendo una copia de su valor y almacenando dicha copia en la ubicación de memoria asociada a la otra variable. Cambiando una no tiene efecto en la otra. Por ejemplo, después de:

Changed lines 30-31 from:

only pin has the value 12; pin2 is still 13.

to:

sólo pin tiene el valor 12; pin2 tiene todavía 12.

June 05, 2010, at 12:29 PM by Equipo Traduccion -
Changed lines 21-23 from:

cambiará el valor de la variable a 12. Observa que no se especifica el tipo de la variable: este no cambia con la asignación. Es decir, el nombre de la variable está permanentemente asociado a un tipo; sólo esto cambia valor. [1] Ten en cuenta que tienes que declarar una variable antes de asignarle un valor. Si se incluye la instrucción precedente en un programa sin la primera declaración anterior, obtendrá un mensaje como: "Error: pin no ha sido declarado en este ámbito". 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".

to:

cambiará el valor de la variable a 12. Observa que no se especifica el tipo de la variable: este no cambia con la asignación. Es decir, el nombre de la variable está permanentemente asociado a un tipo; sólo esto cambia valor. [1] Ten en cuenta que tienes que declarar una variable antes de asignarle un valor. Si se incluye la instrucción anterior en un programa sin la previa declaración anterior, obtendras un mensaje del estilo: "error: pin was not declared in this scope" ("Error: pin no ha sido declarado en este ámbito").

June 05, 2010, at 12:25 PM by Equipo Traduccion -
Added line 21:

cambiará el valor de la variable a 12. Observa que no se especifica el tipo de la variable: este no cambia con la asignación. Es decir, el nombre de la variable está permanentemente asociado a un tipo; sólo esto cambia valor. [1] Ten en cuenta que tienes que declarar una variable antes de asignarle un valor. Si se incluye la instrucción precedente en un programa sin la primera declaración anterior, obtendrá un mensaje como: "Error: pin no ha sido declarado en este ámbito".

June 05, 2010, at 12:19 PM by Equipo Traduccion -
Changed lines 17-18 from:

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:

to:

Una variable tiene otras ventajas sobre un valor como un número. La más importante, puedes cambiar el valor de una variable mediante un asignador (representado por el signo igual). Por ejemplo:

June 05, 2010, at 12:12 PM by Equipo Traduccion -
Changed lines 3-4 from:

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):

to:

Una variable es una ubicación para almacenar una porción de información. Tiene un nombre, un valor y un tipo. Por ejemplo, esta sentencia (llamado una declaración):

Changed lines 7-8 from:

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:

to:

crea una variable cuyo nombre es pin, whose value is 13, y su tipo es int. Mas tarde en el programa, puedes hacer referencia a esta variable por su nombre, momento en el que puedes acceder a su valor y utilizarlo. Por ejemplo, en esta sentencia:

Changed lines 11-12 from:

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:

to:

es el valor de pin (13) el que será pasado a la funciónpinMode(). En este caso, realmente no necesitas usar una variable, esta sentencia funcionaría igual de bien:

Changed lines 15-16 from:

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).

to:

La ventaja de una variable en este caso es que solo necesitas especificar el número del pin una única vez, pero puedes usarlo montones de veces. Así, si mas tarde decides cambiar el pin 13 por el 12, solo tienes que cambiarlo en un punto del código. Además puedes usar un nombre descriptivo que tenga que ver con el uso que vas a dar a la variable (ej. un programa para controlar un LED RGB (Rojo, Verde y Azul) podría tener variables llamada PinRojo, PinVerde y PinAzul).

March 10, 2008, at 01:16 AM by David A. Mellis -
Changed lines 15-16 from:

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.

to:

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).

March 10, 2008, at 01:14 AM by David A. Mellis -
Changed lines 28-29 from:

pin = 12; @]

to:

pin = 12; @]

Changed lines 45-46 from:

} @]

to:

} @]

Changed lines 61-63 from:

} @]

to:

} @]

Changed lines 73-75 from:

} @]

to:

} @]

Changed lines 81-83 from:

} @]

to:

} @]

March 10, 2008, at 01:13 AM by David A. Mellis -
Deleted line 29:
Deleted line 46:
March 10, 2008, at 01:12 AM by David A. Mellis -
Added lines 1-95:

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):

int pin = 13;

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:

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.

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:

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.

Share