126 of 286
112 I2CCmd Type Function returning Integer Invocation I2CCmd(channel, slaveID, writeCnt, writeData, readCnt, readData) Parameter Method Type Description channel ByVal Byte The I2C channel number (0-4). slaveID ByVal Byte The identifier of the I2C slave device (in the 7 high order bits). writeCnt ByVal integral The number of bytes to write (0 – 65535). writeData ByRef any type The variable containing the data to write. readCnt ByVal integral The number of bytes to read (0 – 65535). readData ByRef any type The variable in which to place the data read. Discussion The routine allows you to send and/or receive data from an I2C device. The specified channel must have been previously opened with a call to OpenI2C(). If the channel has not been opened, the results are undefined. If an invalid channel is specified or if both writeCnt and readCnt are zero, the function returns immediately without doing anything and the return value is zero. You may specify the value 0 for writeData or readData if no data is being provided for writing or reading, respectively. If you do this, the corresponding data count parameter must also be zero or the compiler will issue an error message. The execution of the I2C command sequence begins by issuing an I2C start condition on the SDA and SCL lines. Next, if writeCnt is non-zero the given slaveID value is transmitted (with the least significant bit being zero) followed by the specified number of bytes taken from writeData. Then, if readCnt is non-zero the slaveID value is transmitted again but with the least significant bit being one and the specified number of bytes is read from the slave and placed in readData. Finally, an I2C stop condition is issued followed by both the SDA and SCL lines returning to the idle state. The return value may be negative, zero or positive. If the return value is negative it signifies that the slave failed to positively acknowledge one of the transmitted bytes. The value is the negative of the number of bytes that were not successfully transmitted. If the slave fails to positively acknowledge either the slave ID or the first data byte, the return value will be the negative of the writeCnt parameter value. If the return value is non-negative it represents the number of data bytes read from the slave and placed in readData. Example Dim odata(1 to 2) as Byte, idata(1 to 10) as Byte Dim ival as Integer Call OpenI2C (1, 12, 13) odata(1) = &H06 odata(2) = &H00 ival = I2CCmd(1, &H7e, 2, odata(1), 10, idata(1)) Resource Usage This function uses the I/O Timer for channels 1 to 4. If the timer is already in use, the result and the return value are both undefined. Interrupts are disabled for periods of about 9 times the selected I2C bit time plus additional amounts due to slave clock stretching for each byte sent and received (interrupts are reenabled between bytes). However, RTC ticks are accumulated during the process so the RTC should not lose time.