Программирование LEGO NXT роботов на языке NXC - Первая программа — различия между версиями

Материал из roboforum.ru Wiki
Перейти к: навигация, поиск
(Написание программы)
(Написание программы)
Строка 21: Строка 21:
 
==Написание программы==
 
==Написание программы==
 
Теперь введите текст программы:
 
Теперь введите текст программы:
<code language="c++">
+
<code language="cpp">
 
  task main()
 
  task main()
 
  {
 
  {
Строка 32: Строка 32:
 
  }
 
  }
 
</code>
 
</code>
It might look a bit complicated at first, so let us analyze it.
+
На первый взгляд выглядит немного сложно, так что давайте разберемся в ней.
Programs in NXC consist of tasks. Our program has just one task, named main. Each program needs to have a
+
 
task called main which is the one that will be executed by the robot. You will learn more about tasks in Chapter
+
Программы NXC состоят из задач ("task"). Наша программа содержит всего одну задачу с именем "main". Каждая программа должна содержать задачу с именем "main", которая будет исполняться роботом. Вы узнаете больше о задачах в главе 6. Задача состоит из набора команд, называемых также операторами. Операторы заключены в фигурные скобки, чтобы было ясно, что они принадлежат этой задаче. Каждый оператор заканчивается точкой с запятой. Это позволяет понять где кончается один оператор и начинается следующий. В целом задача обычно выглядит следующим образом:
VI. A task consists of a number of commands, also called statements. There are brackets around the statements
+
<code language="cpp">
such that it is clear that they all belong to this task. Each statement ends with a semicolon. In this way it is clear
+
task main()
where a statement ends and where the next statement begins. So a task looks in general as follows:
+
{
task main()
+
statement1;
{
+
statement2;
statement1;
+
statement2;
+
}
+
</code>
}
+
Наша программа содержит 6 операторов. Давайте разберем их по очереди:
Our program has six statements. Let us look at them one at the time:
+
 
OnFwd(OUT_A, 75);
+
OnFwd(OUT_A, 75);
 +
 
 
This statement tells the robot to start output A, that is, the motor connected to the output labeled A on the NXT,
 
This statement tells the robot to start output A, that is, the motor connected to the output labeled A on the NXT,
 
to move forwards. The number following sets the speed of the motor to 75% of maximum speed.
 
to move forwards. The number following sets the speed of the motor to 75% of maximum speed.
OnFwd(OUT_C, 75);
+
 
 +
OnFwd(OUT_C, 75);
 +
 
 
Same statement but now we start motor C. After these two statements, both motors are running, and the robot
 
Same statement but now we start motor C. After these two statements, both motors are running, and the robot
 
moves forwards.
 
moves forwards.
Wait(4000);
+
 
 +
Wait(4000);
 +
 
 
Now it is time to wait for a while. This statement tells us to wait for 4 seconds. The argument, that is, the number
 
Now it is time to wait for a while. This statement tells us to wait for 4 seconds. The argument, that is, the number
 
between the parentheses, gives the number of 1/1000 of a second: so you can very precisely tell the program how
 
between the parentheses, gives the number of 1/1000 of a second: so you can very precisely tell the program how
 
long to wait. For 4 seconds, the program is sleeping and the robot continues to move forwards.
 
long to wait. For 4 seconds, the program is sleeping and the robot continues to move forwards.
OnRev(OUT_AC, 75);
+
 
 +
OnRev(OUT_AC, 75);
 +
 
 
The robot has now moved far enough so we tell it to move in reverse direction, that is, backwards. Note that we
 
The robot has now moved far enough so we tell it to move in reverse direction, that is, backwards. Note that we
 
can set both motors at once using OUT_AC as argument. We could also have combined the first two statements
 
can set both motors at once using OUT_AC as argument. We could also have combined the first two statements
 
this way.
 
this way.
Wait(4000);
+
 
 +
Wait(4000);
 +
 
 
Again we wait for 4 seconds.
 
Again we wait for 4 seconds.
Off(OUT_AC);
+
 
 +
Off(OUT_AC);
 +
 
 
And finally we switch both motors off.
 
And finally we switch both motors off.
 +
 
That is the whole program. It moves both motors forwards for 4 seconds, then backwards for 4 seconds, and
 
That is the whole program. It moves both motors forwards for 4 seconds, then backwards for 4 seconds, and
 
finally switches them off.
 
finally switches them off.
 +
 
You probably noticed the colors when typing in the program. They appear automatically. The colors and styles
 
You probably noticed the colors when typing in the program. They appear automatically. The colors and styles
 
used by the editor when it performs syntax highlighting are customizable.
 
used by the editor when it performs syntax highlighting are customizable.

Версия 14:12, 16 мая 2009

Автор: Daniele Benedettelli

Перевод: © Ботов Антон aka =DeaD=, 2009

Эксклюзивно для www.roboforum.ru
копирование на другие ресурсы и публикация перевода
без разрешения его автора запрещены

Первая программа

В этой главе я покажу как написать очень простую программу. Мы будем программировать робота, чтобы он 4 секунды ехал вперед, потом 4 секунды ехал назад, а потом остановился. Это будет выглядеть не очень впечатляюще, но вы сможете на этом примере получить представления об простейших способах программирования. Кроме того вы сможете понять, насколько это просто. Но, прежде чем писать программу, нам нужно собрать робота.

Постройка робота

Робот, которого мы будем использовать в этом курсе - Tribot, это первый колёсный робот которого инструкция к NXT предлагает вам собрать после покупки набора. Единственное отличие будет заключаться в том, что вы должны подключить правый мотор в порт A, левый мотор в порт C, а мотор захвата в порт B.

Lego NXT Tribot.jpg

Убедитесь, что вы правильно установили драйверы Mindstorms NXT Fantom Drivers, которые поставлялись с набором.

Запуск Bricx Command Center

Мы будем писать программы используя Bricx Command Center. Запустите его двойным щелчком по иконке BricxCC (я предполагаю, что вы уже установили BricxCC. Если нет, загрузите его с сайта (см. введение), и установите его в любой удобный вам каталог). Программа попросит вас предоставить ей возможность подключиться к роботу. Включите робота и нажмите "ОК". Программа (скорее всего) автоматически найдёт робота. После чего интерфейс пользователя будет выглядеть так, как показано ниже (но без закладки с текстовым окном).

BricxCCScreenShot1.jpg

Интерфейс выглядит как стандартный текстовый редактор с обычным меню и кнопками для открытия и сохранения файлов, печати, редактирования и т.п. Но среди них есть несколько специальных меню для компилирования программ и загрузки их в робота, а также для получения информации от робота. Пока вы можете не обращать на них внимание. Мы планируем сейчас написать новую программу. Так что нажимайте кнопку "New File" чтобы открыть новое пустое окно с текстовым редактором.

Написание программы

Теперь введите текст программы:

task main()
{
OnFwd(OUT_A, 75);
OnFwd(OUT_C, 75);
Wait(4000);
OnRev(OUT_AC, 75);
Wait(4000);
Off(OUT_AC);
}

На первый взгляд выглядит немного сложно, так что давайте разберемся в ней.

Программы NXC состоят из задач ("task"). Наша программа содержит всего одну задачу с именем "main". Каждая программа должна содержать задачу с именем "main", которая будет исполняться роботом. Вы узнаете больше о задачах в главе 6. Задача состоит из набора команд, называемых также операторами. Операторы заключены в фигурные скобки, чтобы было ясно, что они принадлежат этой задаче. Каждый оператор заканчивается точкой с запятой. Это позволяет понять где кончается один оператор и начинается следующий. В целом задача обычно выглядит следующим образом:

task main()
{
statement1;
statement2;
…
}

Наша программа содержит 6 операторов. Давайте разберем их по очереди:

OnFwd(OUT_A, 75);

This statement tells the robot to start output A, that is, the motor connected to the output labeled A on the NXT, to move forwards. The number following sets the speed of the motor to 75% of maximum speed.

OnFwd(OUT_C, 75);

Same statement but now we start motor C. After these two statements, both motors are running, and the robot moves forwards.

Wait(4000);

Now it is time to wait for a while. This statement tells us to wait for 4 seconds. The argument, that is, the number between the parentheses, gives the number of 1/1000 of a second: so you can very precisely tell the program how long to wait. For 4 seconds, the program is sleeping and the robot continues to move forwards.

OnRev(OUT_AC, 75);

The robot has now moved far enough so we tell it to move in reverse direction, that is, backwards. Note that we can set both motors at once using OUT_AC as argument. We could also have combined the first two statements this way.

Wait(4000);

Again we wait for 4 seconds.

Off(OUT_AC);

And finally we switch both motors off.

That is the whole program. It moves both motors forwards for 4 seconds, then backwards for 4 seconds, and finally switches them off.

You probably noticed the colors when typing in the program. They appear automatically. The colors and styles used by the editor when it performs syntax highlighting are customizable.

Запуск программы

Once you have written a program, it needs to be compiled (that is, changed into binary code that the robot can understand and execute) and sent to the robot using USB cable or BT dongle (called “downloading” the program). Here you can see the button that allows you to (from left to right) compile, download, run and stop the program. Press the second button and, assuming you made no errors when typing in the program, it will be correctly compiled and downloaded. (If there are errors in your program you will be notified; see below.) Now you can run your program. To this, go to My Files OnBrick menu, Software files, and run 1_simple program. Remember: software files in NXT filesystem have the same name as source NXC file. Also, to get the program run automatically, you can use the shortcut CTRL+F5 or after downloading the program you can press the green run button. Does the robot do what you expected? If not, check wire connections.

Ошибки в программе

When typing in programs there is a reasonable chance that you make some errors. The compiler notices the errors and reports them to you at the bottom of the window, like in the following figure: It automatically selects the first error (we mistyped the name of the motor). When there are more errors, you can click on the error messages to go to them. Note that often errors at the beginning of the program cause other errors at other places. So better only correct the first few errors and then compile the program again. Also note that the syntax highlighting helps a lot in avoiding errors. For example, on the last line we typed Of rather than Off. Because this is an unknown command it is not highlighted. There are also errors that are not found by the compiler. If we had typed OUT_B this would cause the wrong motor to turn. If your robot exhibits unexpected behavior, there is most likely something wrong in your program.

Изменяем скорость

As you noticed, the robot moved rather fast. To change the speed you just change the second parameter inside parentheses. The power is a number between 0 and 100. 100 is the fastest, 0 means stop (NXT servo motors will hold position). Here is a new version of our program in which the robot moves slowly: task main() { OnFwd(OUT_AC, 30); Wait(4000); OnRev(OUT_AC, 30); Wait(4000); Off(OUT_AC); }

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

In this chapter you wrote your first program in NXC, using BricxCC. You should now know how to type in a program, how to download it to the robot and how to let the robot execute the program. BricxCC can do many more things. To find out about them, read the documentation that comes with it. This tutorial will primarily deal with the language NXC and only mention features of BricxCC when you really need them. You also learned some important aspects of the language NXC. First of all, you learned that each program has one task named main that is always executed by the robot. Also you learned the four basic motor commands: OnFwd(), OnRev() and Off(). Finally, you learned about the Wait() statement.