Datasheet
Chapter 8. The I
2
C Library
32
8.3. Sending data to an I
2
C device
Thus to send data to a device the sequence is: starting the transaction, sending the control byte, sending
the data, and stopping the transaction. Once again, it is important to study the device datasheet. Many
devices expect to receive multiple bytes of data in each transaction.
As an example, consider the MCP4726 DAC[MCP6]. This is a 12 bit DAC. Since only 8 bits may be sent
to the device at a time, the data must be broken up into two transmissions, the first sending the high four
bits and the second, the lower eight:
/* Write condition is a zero bit so the control byte is formed
* merely by shifting the address left one bit */
ucControlByte = ucDevice<<1;
/* Break value into two bytes */
ucByteH = uValue >> 8;
ucByteL = uValue & 0xff;
StartI2C(); /* Start I2C transaction */
WriteI2C(ucControlByte); /* Address of MCP4726 | write */
WriteI2C(ucByteH); /* high 4 bits of value */
WriteI2C(ucByteL); /* Low 8 bits of value */
StopI2C(); /* Stop the transaction */
8.4. Reading data from an I
2
C device
Reading data is a bit more complex. The master must send the control byte as usual, and often,
must send the slave some indication of what information is needed. The master must then restart the
transaction and send the control byte, this time with the read bit set. The master (dsPIC) may then read
the data from the device. The data must then be acknowledged or not acknowledged by the master before
stopping the transaction. In many cases, the default is to not acknowledge (NAK) the data, because an
acknowledge (ACK) is a signal to the device to send more data! Again, it is critically important to become
familiar with the device datasheet.
Consider the MCP23008 I/O extender[MCP5]. The master must start the transaction, send the control
byte, then send the register whose contents are desired. Then the transaction is restarted, the data
fetched from the slave, and a NAK sent. Finally the transaction may be stopped. Should the master have
sent an ACK, the 23008 would then send the contents of the next register:
/* Write condition is a zero bit so the control byte is formed
* merely by shifting the address left one bit */
ucControlByte = ucDevice<<1;
StartI2C(); /* Start I2C transaction */
WriteI2C( ucControlByte ); /* Send bus Address */
WriteI2C( ucRegister ); /* Address of desired register */
RestartI2C(); /* Restart so can send read */
WriteI2C( ucControlByte+1 );/* Send bus address with read bit */
ucResult = getI2C(); /* Get answer from MCP23008 */
NotAckI2C(); /* NAK result to stop answers */
StopI2C(); /* Send stop on bus */