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

Материал из roboforum.ru Wiki
Версия от 03:52, 20 мая 2009; =DeaD= (обсуждение | вклад) (Дополнительная информация о сенсорах)
Перейти к: навигация, поиск

Автор: Daniele Benedettelli

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

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

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

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

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

Команда SetSensor(), которую мы видели ранее, реально делает две вещи: она устанавливает тип сенсора и режим, в котором этот сенсор будет работать. Путём установки режима и типа сенсора отдельными полями вы можете более точно контролировать поведение сенсора, что полезно в различных задачах. The type of the sensor is set with the command SetSensorType(). There are many different types, but I will report the main ones: SENSOR_TYPE_TOUCH, which is the touch sensor, SENSOR_TYPE_LIGHT_ACTIVE, which is the light sensor (with led on), SENSOR_TYPE_SOUND_DB, which is the sound sensor, and SENSOR_TYPE_LOWSPEED_9V, which is the Ultrasonic sensor. Setting the type sensor is in particular important to indicate whether the sensor needs power (e.g. to light up led in the light sensor), or to indicate NXT that the sensor is digital and needs to be read via I2C serial protocol. It is possible to use old RCX sensor with NXT: SENSOR_TYPE_TEMPERATURE, for the temperature sensor, SENSOR_TYPE_LIGHT for old light sensor, SENSOR_TYPE_ROTATION for RCX rotation sensor (this type will be discussed later). The mode of the sensor is set with the command SetSensorMode(). There are eight different modes. The most important one is SENSOR_MODE_RAW. In this mode, the value you get when checking the sensor is a number between 0 and 1023. It is the raw value produced by the sensor. What it means depends on the actual sensor. For example, for a touch sensor, when the sensor is not pushed the value is close to 1023. When it is fully pushed, it is close to 50. When it is pushed partially the value ranges between 50 and 1000. So if you set a touch sensor to raw mode you can actually find out whether it is touched partially. When the sensor is a light sensor, the value ranges from about 300 (very light) to 800 (very dark). This gives a much more precise value than using the SetSensor() command. For details, see the NXC Programming Guide. The second sensor mode is SENSOR_MODE_BOOL. In this mode the value is 0 or 1. When the raw value is above 562 the value is 0, otherwise it is 1. SENSOR_MODE_BOOL is the default mode for a touch sensor, but can be used for other types, discarding analogic informations. The modes SENSOR_MODE_CELSIUS and SENSOR_MODE_FAHRENHEIT are useful with temperature sensors only and give the temperature in the indicated way. SENSOR_MODE_PERCENT turns the raw value into a value between 0 and 100. SENSOR_MODE_PERCENT is the default mode for a light sensor. SENSOR_MODE_ROTATION is used only for the rotation sensor (see below). 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.