Using Multiple Ultrasonic Sensors
If you wish to use Multiple Ultrasonic Sensors on your NXT Robot, you need to program them so only ONE Sensor is taking a measurement at any time. If you have all the Ultrasonic Sensors on at once they interfere with each other and give incorrect readings. To get around this you need to take advantage of the Sensors Mode 3: Event Capture Mode.
I was surprised to find that the was virtually no data on the NXT's Ultrasonic Sensor Modes available on the Internet. But with the help of the Lego Mindstorms NXT Hardware Developer Kit, Appendix 7: LEGO MINDSTORMS NXT Ultrasonic Sensor I2C communication protocol.pdf, I was able to solve it relatively easily. Consult the NXC API for using I2C Command & Control
Official Lego I2C Commands Extract for Ultrasonic Sensor:
- Single shot command:
- Continuous measurement command:
- Event capture command:
In this mode the ultrasonic sensor will only make a new measurement every time the command byte is send to the sensor. The sensor will measure distances for up to 8 objects and save the distances within the “Read measurement byte 0 – 7”.
This is the default mode, where the sensor continuously makes new measurement with the specified interval.
Within this mode the sensor will measure whether any other ultrasonic sensors are within the vicinity. With this information a program can evaluate when it is best to make a new measurement which will not conflict with other ultrasonic sensors.
To use the Ultrasonic Sensor's "Mode 3" with NXC, you need to use I2CWrite(PORTnumber, 0×41, 0×03) to turn on and initialise the sensor. You can the then use SensorUS(PORTnumber) to read the distance to object. To turn the Sensor Off again, you need to use I2CWrite(PORTnumber, 0×41, 0×00). You need to repeat these commands for each Ultrasonic Sensor you are using. It pays to initialise all your Ultrasonic Sensors to the Off state when the program starts.