Программирование LEGO NXT роботов на языке NXC - Использование переменных

Материал из roboforum.ru Wiki
Версия от 20:00, 16 мая 2009; =DeaD= (обсуждение | вклад) (Создана новая страница размером =Использование переменных= Variables form a very important aspect of every programming language. Variables are memo...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Использование переменных

Variables form a very important aspect of every programming language. Variables are memory locations in which we can store a value. We can use that value at different places and we can change it. Let us describe the use of variables using an example.

Движение по спирали

Assume we want to adapt the above program in such a way that the robot drives in a spiral. This can be achieved by making the time we sleep larger for each next straight movement. That is, we want to increase the value of MOVE_TIME each time. But how can we do this? MOVE_TIME is a constant and therefore cannot be changed. We need a variable instead. Variables can easily be defined in NXC. Here is the spiral program.

  1. define TURN_TIME 360

int move_time; // define a variable task main() { move_time = 200; // set the initial value repeat(50) { OnFwd(OUT_AC, 75); Wait(move_time); // use the variable for sleeping OnRev(OUT_C, 75); Wait(TURN_TIME); move_time += 200; // increase the variable } Off(OUT_AC); } The interesting lines are indicated with the comments. First we define a variable by typing the keyword int followed by a name we choose. (Normally we use lower-case letters for variable names and uppercase letters for constants, but this is not necessary.) The name must start with a letter but can contain digits and the underscore sign. No other symbols are allowed. (The same applied to constants, task names, etc.) The word int stands for integer. Only integer numbers can be stored in it. In the second line we assign the value 200 to the variable. From this moment on, whenever you use the variable, its value will be 200. Now follows the repeat loop in which we use the variable to indicate the time to sleep and, at the end of the loop we increase the value of the variable by 200. So the first time the robot sleeps 200 ms, the second time 400 ms, the third time 600 ms, and so on. Besides adding values to a variable we can also multiply a variable with a number using *=, subtract using -= and divide using /=. (Note that for division the result is rounded to the nearest integer.) You can also add one variable to the other, and write down more complicated expressions. The next example does not have any effect on your robot hardware, since we don't know how to use the NXT display yet!

int aaa; int bbb,ccc; int values[]; task main() { aaa = 10; bbb = 20 * 5; ccc = bbb; ccc /= aaa; ccc -= 5; aaa = 10 * (ccc + 3); // aaa is now equal to 80 ArrayInit(values, 0, 10); // allocate 10 elements = 0 values[0] = aaa; values[1] = bbb; values[2] = aaa*bbb; values[3] = ccc; } Note on the first two lines that we can define multiple variables in one line. We could also have combined all three of them in one line. The variable named values is an array, that is, a variable that contains more than a number: an array can be indexed with a number inside square brackets. In NXC integer arrays are declared so: int name[]; Then, this line allocates 10 elements initializing them to 0. ArrayInit(values, 0, 10);

Случайные числа

In all the above programs we defined exactly what the robot was supposed to do. But things get a lot more interesting when the robot is going to do things that we don't know. We want some randomness in the motions. In NXC you can create random numbers. The following program uses this to let the robot drive around in a random way. It constantly drives forwards for a random amount of time and then makes a random turn. int move_time, turn_time; task main() { while(true) { move_time = Random(600); turn_time = Random(400); OnFwd(OUT_AC, 75); Wait(move_time); OnRev(OUT_A, 75); Wait(turn_time); } } The program defines two variables, and then assigns random numbers to them. Random(600) means a random number between 0 and 600 (the maximum value is not included in the range of numbers returned). Each time you call Random the numbers will be different. Note that we could avoid the use of the variables by writing directly e.g. Wait(Random(600)). You also see a new type of loop here. Rather that using the repeat statement we wrote while(true). The while statement repeats the statements below it as long as the condition between the parentheses is true. The special word true is always true, so the statements between the brackets are repeated forever (or at least until you press the dark grey button on NXT). You will learn more about the while statement in Chapter IV.

Подводим итоги

In this chapter you learned about the use of variables and arrays. You can declare other data types than int: short, long, byte, bool and string. You also learned how to create random numbers, such that you can give the robot unpredictable behavior. Finally we saw the use of the while statement to make an infinite loop that goes on forever.