Initiates an I²C write to the device at the specified address
Device
Name | Type | Description |
---|---|---|
deviceAddress | Integer |
The 8-bit I²C base address
|
registerPlusData | String |
The I²C sub-address and data, or "" for none
|
Integer — 0 for success, or an I²C Error Code
The first two characters of the string to be written via the I²C bus are typically used as the most-significant byte and the least-significant byte of the sub-address — typically the device register you wish to access. A peripheral with 8-bit registers needs only a single byte for its address. An empty string, ""
, may be passed to initiate an empty-payload write phase.
Though the registerPlusData parameter takes a string, this can easily be used to send binary data if you use any of a number of simple conversion processes, as listed below. Pick the one that most closely aligns with how you are storing your binary data:
local sendStringOne = format("%c%c%c", 0xA5, 0xD3, 0x00);
local sendStringTwo = integerOne.tochar() + integerTwo.tochar();
locat sendStringThree = blobOne.tostring();
Squirrel strings can include NULL characters (unlike C strings) so you can send any binary value this way.
On completion, 0 is returned for success, or non-zero for an error condition. A list of error codes can be found on the i2c.readerror() page.
Please note that many vendors’ device datasheets specify a 7-bit base I²C address. In this case, you will need to bit-shift the address left by 1 (ie. multiply it by 2) to form the 8-bit address required by the imp API:
local impReadyI2Caddress = datasheetI2Caddress << 1;
The code below provides an example of using an I²C device. It configures an SA56004X temperature sensor — as found on the Hannah R2 reference design — by requesting the CLOCK_SPEED_400_KHZ clocking rate.