I2C Memory units

LEGO defines its digital sensors (for now, the only existing one being the Ultrasonic radar) as simple memory units. This memory is organized in a certain way and can be accessed almost randomly. Almost, because the experience showed that the radar's memory must be accessed at precise addresses only and will have an undefined behavior if trying to access its memory at a non recognized address. Anyway, this is not a concern for the I2C Memory driver, which provides generic read and write functions to match all possible needs of remove I2C memory units.

Granted the I2C SoftMAC driver and its transaction mechanism, the I2C Memory driver code is pretty straightforward and simply creates I2C transactions to the remote device accordingly.

Usage

Using the I2C Memory driver is very simple. The radar driver is itself a very good example since it's entirely based on the basic features provided by the I2C Memory driver. First, you need to initialize the remote device on the given sensor port :

nx_i2c_memory_init(sensor);

This will trigger the underlying I2C initialization mechanism for this sensor port and enable I2C communication with the device until you close the memory unit. Then, you can do any reads and writes you want to this memory unit. Let's say you want to read the value (1 byte) at 0x50, change it and write it back. You would do :

U8 addr = 0x50;
U8 value;

// Read the value
nx_i2c_memory_read(sensor, addr, &value, 1);

// Change it, and write it back to the same address
value++;
nx_i2c_memory_write(sensor, addr, &value, 1);

At the very end, when you don't need the memory unit and want to release the sensor port, just call :

nx_i2c_memory_close(sensor);

And you're done!