I2C
 

 

Library

#include <I2C.bas>

I

 
Interface
 
SUB I2CIN ( DATApin, CLKpin, addr, OUTcnt, BYREF OUTlist as string, INcnt, BYREF INlist as string)

FUNCTION I2COUT (DATApin, CLKpin, addr, OUTcnt, BYREF OUTlist as string)
 
#define I2Cspeed100                 ' add this statement before the #include <I2C.bas> for 100 Kb shift rate
#define I2Cspeed50                   ' for 50 Kb shift rate
#define I2CslaveCLKstretch        ' trial code to support slave clock stretching (unverified on a slave that stretches clocks)
 
Description
 
These libraries are written for single master operation of the ARM talking to possible multiple slaves selected by address.
 
I2CIN will send OUTcnt bytes from OUTlist and then receives INlist bytes as i2c serial data on CLKpin and DATApin from the i2c device at addr. OUTcnt may be -1 and OUTlist empty. If OUTcnt is 0, then the string will be sent until a 0, CR or LF character is found in OUTlist .

INcnt bytes will be received. If INcnt is 0, then the string will be filled with bytes until a 0, CR or LF character is received.  Note that no bounds checking is performed on the input, and if a 0, CR, or LF is never received then this routine will hang.    As there is no bounds checking its possible to overwrite other variables, if less than 256 bytes have been allocated for the InputList string.

I2COUT will send OUTcnt bytes from OUTlist bytes as i2c serial data on CLKpin and DATApin to the i2c device at addr.  If OUTcnt is 0, then the string will be sent until a 0, CR or LF character is found in OUTlist.  If the i2c device does not respond 0 is returned by I2COUT, otherwise 1.

The data rate is 300Kb.



 
Example

#include <I2C.bas>
...

DIM shortMessage(20) as STRING
DIM shortResponse(20) as STRING


' test the EEPROM 24LC02 on pins 0 == SDA and 1 == SCL
shortMessage(0)= 0                  ' address into EEPROM
shortMessage(1)= 11                ' data
shortMessage(2)= 22
shortMessage(3)= 33
shortMessage(5)= 44
shortMessage(6)= 55
shortMessage(7)= 66

present = I2COUT (0, 1, 0xA0, 8, shortMessage) 
if present = 0 then print "NO i2c device ***"

WAIT(10) ' allow time for data to be written
I2CIN(0, 1, 0xA0, 1,shortMessage, 7, shortResponse)  

' now do I2CIN as separate operations

I2COUT (0, 1, 0xA0, 1, shortMessage)   ' send just the address and offset 
I2CIN(0, 1, 0xA0, -1,"", 7, shortResponse)