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

Материал из roboforum.ru Wiki
Перейти к: навигация, поиск

Автор: 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

We write our programs using Bricx Command Center. Start it by double clicking on the icon BricxCC. (I assume you already installed BricxCC. If not, download it from the web site (see the preface), and install it in any directory you like. The program will ask you where to locate the robot. Switch the robot on and press OK. The program will (most likely) automatically find the robot. Now the user interface appears as shown below (without the text tab). The interface looks like a standard text editor, with the usual menu, and buttons to open and save files, print files, edit files, etc. But there are also some special menus for compiling and downloading programs to the robot and for getting information from the robot. You can ignore these for the moment. We are going to write a new program. So press the New File button to create a new, empty window.

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

Now type in the following program: task main() { OnFwd(OUT_A, 75); OnFwd(OUT_C, 75); Wait(4000); OnRev(OUT_AC, 75); Wait(4000); Off(OUT_AC); } 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 VI. A task consists of a number of commands, also called statements. There are brackets around the statements such that it is clear that they all belong to this task. Each statement ends with a semicolon. In this way it is clear where a statement ends and where the next statement begins. So a task looks in general as follows: task main() { statement1; statement2; … } Our program has six statements. Let us look at them one at the time: 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.