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

Материал из roboforum.ru Wiki
Версия от 04:08, 20 мая 2009; =DeaD= (обсуждение | вклад) (Режимы и типы сенсоров)
Перейти к: навигация, поиск

Автор: Daniele Benedettelli

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

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

Дополнительная информация о сенсорах

В главе 5 мы обсудили простейшие приёмы использования сенсоров, но на самом деле с ними можно делать намного больше. В этой главе мы обсудим отличие между режимом и типом сенсора, увидим как использовать старые RCX-совместимые сенсоры и подключать их к блоку NXT используя кабели "Lego converter cable".

Режимы и типы сенсоров

Команда SetSensor(), которую мы видели ранее, реально делает две вещи: она устанавливает тип сенсора и режим, в котором этот сенсор будет работать. Путём установки режима и типа сенсора отдельными полями вы можете более точно контролировать поведение сенсора, что полезно в различных задачах.

Тип сенсора устанавливается командой SetSensorType(). Существует множество различных типов, но я опишу только основные:

  • SENSOR_TYPE_TOUCH, сенсор касания,
  • SENSOR_TYPE_LIGHT_ACTIVE, датчик освещенности (с включенным светодиодом, т.е. работающий по отраженному свету),
  • SENSOR_TYPE_SOUND_DB, датчик звука и
  • SENSOR_TYPE_LOWSPEED_9V - ультразвуковой дальномер.

Установка типа сенсора важна для определения нужно ли подавать питание (включает светодиод в датчике освещенности), или для указания модулю NXT, что сенсор цифровой и надо работать с ним по протоколу I2C. Кроме всего прочего допускается использование с NXT сенсоров из старого набора, поставляемого с модулем RCX:

  • SENSOR_TYPE_TEMPERATURE, датчик температуры,
  • SENSOR_TYPE_LIGHT - старый датчик освещенности,
  • SENSOR_TYPE_ROTATION - датчик положения вала (датчик вращения) - этот тип мы обсудим позже.

Режим датчика задаётся командой SetSensorMode(). Существует 8 различных режимов. Наиболее важный - это SENSOR_MODE_RAW. В этом режиме, значение, которое вы получаете от сенсора является числом и лежит в диапазоне 0..1023. Это исходное значение, которое выдаёт датчик. Что оно означает - зависит от того, какой датчик подключен. Например, для датчика касания, когда он не нажат, значение близко к 1023, а когда полностью нажат - близко к 50. При частичном нажатии значение варьируется между 50 и 1000. Так что если вы установите датчик касания в этот режим, вы сможете определять, когда датчик нажат частично. С датчиком освещенности значение варьируется между 300 (очень светло) и 800 (очень темно). Это даёт гораздо значение большей точности, чем при использовании команды SetSensor(). Для более подробной информации смотрите инструкцию по программированию к языку NXC.

Второй режим работы сенсоров - SENSOR_MODE_BOOL. В этом режиме возвращаемое значение 0 или 1. Оно получается из исходного значения 0..1023 сравнением, если меньше 565, возвращается 0, иначе 1. SENSOR_MODE_BOOL является режимом по умолчанию для датчика касания, но может быть быть применен к любому другому сенсору, чтобы убрать аналоговую информацию и оставить двоичный ответ. Режимы SENSOR_MODE_CELSIUS и SENSOR_MODE_FAHRENHEIT полезны только для датчиков температуры и дают ответ в соответствующих единицах измерения. SENSOR_MODE_PERCENT превращает исходное значение 0..1023 в значение между 0 и 100, просто деля его на 1023. SENSOR_MODE_PERCENT является режимом по умолчанию для датчика освещенности. SENSOR_MODE_ROTATION используется только для сенсора вращения (см. ниже).

There are two other interesting modes: SENSOR_MODE_EDGE and SENSOR_MODE_PULSE. They count transitions, that is, changes from a low to a high raw value or opposite. For example, when you touch a touch sensor this causes a transition from high to low raw value. When you release it you get a transition the other direction. When you set the sensor mode to SENSOR_MODE_PULSE, only transitions from low to high are counted. So each touch and release of the touch sensor counts for one. When you set the sensor mode to SENSOR_MODE_EDGE, both transitions are counted. So each touch and release of the touch sensor counts for two. So you can use this to count how often a touch sensor is pushed. Or you can use it in combination with a light sensor to count how often a (strong) lamp is switched on and off. Off course, when you are counting edges or pulses, you should be able to set the counter back to 0. For this you use the command ClearSensor(), that clears the counter for the indicated sensor.

Let us look at an example. The following program uses a touch sensor to steer the robot. Connect the touch sensor with a long wire to input one. If touch the sensor quickly twice the robot moves forwards. It you touch it once it stops moving.

task main()
{
  SetSensorType(IN_1, SENSOR_TYPE_TOUCH);
  SetSensorMode(IN_1, SENSOR_MODE_PULSE);
  while(true)
  {
    ClearSensor(IN_1);
    until (SENSOR_1 > 0);
    Wait(500);
    if (SENSOR_1 == 1) {Off(OUT_AC);}
    if (SENSOR_1 == 2) {OnFwd(OUT_AC, 75);}
  }
}

Note that we first set the type of the sensor and then the mode. It seems that this is essential because changing the type also affects the mode.

Сенсор вращения

The rotation sensor is a very useful type of sensor: it is an optical encoder, almost the same as the one built inside NXT servomotors. The rotation sensor contains a hole through which you can put an axle, whose relative angular position is measured. One full rotation of the axle counts 16 steps (or –16 if you rotate it the other way), that means a 22.5 degrees resolution, very rough respect to the 1-degree resolution of the servomotor. This old kind of rotation sensor can be still useful to monitor an axle without the need to waste a motor; also consider that using a motor as encoder requires a lot of torque to move it, while old rotation sensor is very easy to rotate. If you need finer resolution than 16 steps per turn, you can always use gears to mechanically increase the number of ticks per turn. Next example is inherited from old tutorial for RCX. One standard application is to have two rotation sensors connected to the two wheels of the robot that you control with the two motors. For a straight movement you want both wheels to turn equally fast. Unfortunately, the motors normally don't run at exactly the same speed. Using the rotation sensors you can see that one wheel turns faster. You can then temporarily stop that motor (best using Float()) until both sensors give the same value again. The following program does this. It simply lets the robot drive in a straight line. To use it, change your robot by connecting the two rotation sensors to the two wheels. Connect the sensors to input 1 and 3. task main() { SetSensor(IN_1, SENSOR_ROTATION); ClearSensor(IN_1); SetSensor(IN_3, SENSOR_ROTATION); ClearSensor(IN_3); while (true) { if (SENSOR_1 < SENSOR_3) {OnFwd(OUT_A, 75); Float(OUT_C);} else if (SENSOR_1 > SENSOR_3) {OnFwd(OUT_C, 75); Float(OUT_A);} else {OnFwd(OUT_AC, 75);} } } The program first indicates that both sensors are rotation sensors, and resets the values to zero. Next it starts an infinite loop. In the loop we check whether the two sensor readings are equal. If they are the robot simply moves forwards. If one is larger, the correct motor is stopped until both readings are again equal. Clearly this is only a very simple program. You can extend this to make the robot drive exact distances, or to let it make very precise turns.

Подключение нескольких сенсоров к одному входу

A little disclaimer is needed at the top of this section! Due to the new structure of improved NXT sensors and 6- wires cables, it is not easy as before (as was for RCX) to connect more sensors to the same port. In my honest opinion, the only reliable (and easy to do) application would be to build a touch sensor analog multiplexer to use in combination with a converter cable. The alternative is a complex digital multiplexer that can manage I2C communication with NXT, but this is not definitely an affordable solution for beginners. The NXT has four inputs to connect sensors. When you want to make more complicated robots (and you bought some extra sensors) this might not be enough for you. Fortunately, with some tricks, you can connect two (or even more) sensors to one input. The easiest is to connect two touch sensors to one input. If one of them (or both) is touched the value is 1, otherwise it is 0. You cannot distinguish the two but sometimes this is not necessary. For example, when you put one touch sensor at the front and one at the back of the robot, you know which one is touched based on the direction the robot is driving in. But you can also set the mode of the input to raw (see above). Now you can get a lot more information. If you are lucky, the value when the sensor is pressed is not the same for both sensors. If this is the case you can actually distinguish between the two sensors. And when both are pressed you get a much lower value (around 30) so you can also detect this. You can also connect a touch sensor and a light sensor to one input (RCX sensors only). Set the type to light (otherwise the light sensor won't work). Set the mode to raw. In this case, when the touch sensor is pushed you get a raw value below 100. If it is not pushed you get the value of the light sensor, which is never below 100. The following program uses this idea. The robot must be equipped with a light sensor pointing down, and a bumper at the front connected to a touch sensor. Connect both of them to input 1. The robot will drive around randomly within a light area. When the light sensor sees a dark line (raw value > 750) it goes back a bit. When the touch sensor touches something (raw value below 100) it does the same. Here is the program:

mutex moveMutex; int ttt,tt2; task moverandom() { while (true) { ttt = Random(500) + 40; tt2 = Random(); Acquire(moveMutex); if (tt2 > 0) { OnRev(OUT_A, 75); OnFwd(OUT_C, 75); Wait(ttt); } else { OnRev(OUT_C, 75); OnFwd(OUT_A, 75); Wait(ttt); } ttt = Random(1500) + 50; OnFwd(OUT_AC, 75); Wait(ttt); Release(moveMutex); } } task submain() { SetSensorType(IN_1, SENSOR_TYPE_LIGHT); SetSensorMode(IN_1, SENSOR_MODE_RAW); while (true) { if ((SENSOR_1 < 100) || (SENSOR_1 > 750)) { Acquire(moveMutex); OnRev(OUT_AC, 75); Wait(300); Release(moveMutex); } } } task main() { Precedes(moverandom, submain); } I hope the program is clear. There are two tasks. Task moverandom makes the robot move around in a random way. The main task first starts moverandom, sets the sensor and then waits for something to happen. If the sensor reading gets too low (touching) or too high (out of the white area) it stops the random moves, backs up a little, and start the random moves again.

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

In this chapter we have seen a number of additional issues about sensors. We saw how to separately set the type and mode of a sensor and how this could be used to get additions information. We learned how to use the rotation sensor. And we saw how multiple sensors can be connected to one input of the NXT. All these tricks are extremely useful when constructing more complicated robots. Sensors always play a crucial role there.