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

Материал из roboforum.ru Wiki
Перейти к: навигация, поиск
(Сенсоры)
(Действия при срабатывании сенсора касания)
Строка 23: Строка 23:
  
 
==Действия при срабатывании сенсора касания==
 
==Действия при срабатывании сенсора касания==
Let us now try to make the robot avoid obstacles. Whenever the robot hits an object, we let it move back a bit,
+
Давайте теперь попытаемся сделать так, чтобы робот избегал препятствия. Когда робот будет сталкиваться с препятствием, мы сделаем чтобы он отъезжал немного назад, поворачивался и продолжал движение. Вот программа, которая это реализует:
make a turn, and then continue. Here is the program:
+
task main()
task main()
+
{
{
+
  SetSensorTouch(IN_1);
SetSensorTouch(IN_1);
+
  OnFwd(OUT_AC, 75);
OnFwd(OUT_AC, 75);
+
  while (true)
while (true)
+
  {
{
+
    if (SENSOR_1 == 1)
if (SENSOR_1 == 1)
+
    {
{
+
      OnRev(OUT_AC, 75); Wait(300);
OnRev(OUT_AC, 75); Wait(300);
+
      OnFwd(OUT_A, 75); Wait(300);
OnFwd(OUT_A, 75); Wait(300);
+
      OnFwd(OUT_AC, 75);
OnFwd(OUT_AC, 75);
+
    }
}
+
  }
}
+
}
}
+
 
As in the previous example, we first indicate the type of the sensor. Next the robot starts moving forwards. In the
+
Как и в предыдущем примере, мы сначала определяем тип сенсора, затем робот начинает ехать вперед, а дальше в бесконечном цикле мы постоянно проверяем не оказался ли нажатым контактный сенсор, и если это так - движемся назад 0.3 секунды, поворачиваем направо в течение 0.3 секунд и затем продолжаем движение вперед.
infinite while loop we constantly test whether the sensor is touched and, if so, move back for 300ms, turn right
 
for 300ms, and then continue forwards again.
 
  
 
==Сенсор освещенности==
 
==Сенсор освещенности==

Версия 13:13, 17 мая 2009

Автор: Daniele Benedettelli

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

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

Сенсоры

Разумеется вы можете подключить сенсоры к модулю NXT чтобы робот реагировал на внешние события. Перед тем как я покажу вам, как это сделать, мы должны немного модифицировать робота, добавив ему сенсор касания. Как и ранее, используйте инструкцию по сборке Tribot'а для сборки переднего бампера.

NXT-Tribot-sens1.jpg

Соедините полученный сенсор касания со входом 1 на модулей NXT.

Ждём информацию с сенсора

Давайте начнем с простой программы по которой робот будет ехать вперед, пока не коснётся чего-нибудь. Вот её текст:

task main()
{
  SetSensor(IN_1,SENSOR_TOUCH);
  OnFwd(OUT_AC, 75);
  until (SENSOR_1 == 1);
  Off(OUT_AC);
}

В этой программе две строки для нас особо интересны. Первая строка программы указывает роботу какой тип сенсора мы используем. IN_1 это номер входа, к которому подключен сенсор. Другие входы для сенсоров имеют названия IN_2, IN_3 и IN_4. Идентификатор SENSOR_TOUCH показывает что это сенсор касания. Для датчика света мы будем использовать SENSOR_LIGHT. После того как мы указали тип сенсора и куда он подключен, программа включает оба мотора и робот начинает ехать вперед. Следующий оператор очень полезен. Он ожидает пока условие внутри его круглых скобок не станет истинным. Указанное там условие говорит что значение сенсора SENSOR_1 должно быть равно 1, что означает, что сенсор нажат. Пока сенсор не будет нажат, значение сенсора будет 0. Таким образом этот оператор ждёт нажатия сенсора. После чего оба мотора выключаются и задача считается завершенной.

Действия при срабатывании сенсора касания

Давайте теперь попытаемся сделать так, чтобы робот избегал препятствия. Когда робот будет сталкиваться с препятствием, мы сделаем чтобы он отъезжал немного назад, поворачивался и продолжал движение. Вот программа, которая это реализует:

task main()
{
  SetSensorTouch(IN_1);
  OnFwd(OUT_AC, 75);
  while (true)
  {
    if (SENSOR_1 == 1)
    {
      OnRev(OUT_AC, 75); Wait(300);
      OnFwd(OUT_A, 75); Wait(300);
      OnFwd(OUT_AC, 75);
    }
  }
}

Как и в предыдущем примере, мы сначала определяем тип сенсора, затем робот начинает ехать вперед, а дальше в бесконечном цикле мы постоянно проверяем не оказался ли нажатым контактный сенсор, и если это так - движемся назад 0.3 секунды, поворачиваем направо в течение 0.3 секунд и затем продолжаем движение вперед.

Сенсор освещенности

Besides the touch sensor, you also get a light sensor, a sound sensor and a digital ultrasonic sensor with Mindstorms NXT system. The light sensor can be triggered to emit light or not, so you can measure the amount of reflected light or ambient light in a particular direction. Measuring reflected light is particularly useful when making a robot follow a line on the floor. This is what we are going to do in the next example. To go on with experiments, finish building Tribot. Connect light sensor to input 3, sound sensor to input 2 and ultrasonic sensor to input 4, as indicated by instructions.

We also need the test pad with the black track that comes with the NXT set. The basic principle of line following is that the robot keeps trying to stay right on the border of the black line, turning away from line if the light level is too low (and sensor is in the middle of the line) and turning towards the line if the sensor is out of the track and detects a high light level. Here is a very simple program doing line following with a single light threshold value.

  1. define THRESHOLD 40

task main() { SetSensorLight(IN_3); OnFwd(OUT_AC, 75); while (true) { if (Sensor(IN_3) > THRESHOLD) { OnRev(OUT_C, 75); Wait(100); until(Sensor(IN_3) <= THRESHOLD); OnFwd(OUT_AC, 75); } } } The program first configures port 3 as a light sensor. Next it sets the robot to move forwards and goes into an infinite loop. Whenever the light value is bigger than 40 (we use a constant here such that this can be adapted easily, because it depends a lot on the surrounding light) we reverse one motor and wait till we are on the track again. As you will see when you execute the program, the motion is not very smooth. Try adding a Wait(100) command before the until command to make the robot move better. Note that the program does not work for moving counter-clockwise. To enable motion along arbitrary path a much more complicated program is required. To read ambient light intensity with led off, configure sensor as follows: SetSensorType(IN_3,IN_TYPE_LIGHT_INACTIVE); SetSensorMode(IN_3,IN_MODE_PCTFULLSCALE); ResetSensor(IN_3);

Звуковой сенсор

Using the sound sensor you can transform your expensive NXT set into a clapper! We are going to write a program that waits for a loud sound, and drives the robot until another sound is detected. Attach the sound sensor to port 2, as described in Tribot instructions guide.

  1. define THRESHOLD 40
  2. define MIC SENSOR_2

task main() { SetSensorSound(IN_2); while(true){ until(MIC > THRESHOLD); OnFwd(OUT_AC, 75); Wait(300); until(MIC > THRESHOLD); Off(OUT_AC); Wait(300); } } We first define a THRESHOLD constant and an alias for SENSOR_2; in the main task, we configure the port 2 to read data from the sound sensor and we start a forever loop. Using the until statement, the program waits for the sound level to be greater than the threshold we chose: note that SENSOR_2 is not just a name, but a macro that returns the sound value read from the sensor. If a loud sound occurs, the robot starts to go straight until another sound stops it. The wait statements have been inserted because otherwise the robot would start and stop instantly: in fact, the NXT is so fast that takes no time to execute lines between the two until statements. If you try to comment out the first and the second wait, you will understand this better. An alternative to the use of until to wait for events is while, it is enough to put inside the parentheses a complementary condition, e.g. while(MIC <= THRESHOLD). There is not much more to know about NXT analog sensors; just remember that both light and sound sensors give you a reading from 0 to 100.

Ультразвуковой дальномер

Ultrasonic sensor works as a sonar: roughly speaking, it sends a burst of ultrasonic waves and measures the time needed for the waves to be reflected back by the object in sight. This is a digital sensor, meaning it has an embedded integrated device to analyze and send data. With this new sensor you can make a robot see and avoid an obstacle before actually hitting it (as is for touch sensor).

  1. define NEAR 15 //cm

task main(){ SetSensorLowspeed(IN_4); while(true){ OnFwd(OUT_AC,50); while(SensorUS(IN_4)>NEAR); Off(OUT_AC); OnRev(OUT_C,100); Wait(800); } } The program initializes port 4 to read data from digital US sensor; then runs forever a loop where robots goes straight until something nearer than NEAR cm (15cm in our example) is in sight, then backups a bit and begins going straight again.

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

In this chapter you have seen how to work with all sensors included in NXT set. We also saw how until and while commands are useful when using sensors. I recommend you to write a number of programs by yourself at his point. You have all the ingredients to give your robots pretty complicated behavior now: try to translate in NXC the simplest programs shown in NXT retail software Robo Center programming guide.