Mistake on this page?
Report an issue in GitHub or email us

I2CSlave

Use I2C Slave to communicate with I2C Master.

Synchronization level: not protected.

I2CSlave class reference

Public Member Functions
 I2CSlave (PinName sda, PinName scl)
 Create an I2C Slave interface, connected to the specified pins. More...
void frequency (int hz)
 Set the frequency of the I2C interface. More...
int receive (void)
 Check if this I2C Slave has been addressed. More...
int read (char *data, int length)
 Read specified number of bytes from an I2C master. More...
int read (void)
 Read a single byte from an I2C master. More...
int write (const char *data, int length)
 Write to an I2C master. More...
int write (int data)
 Write a single byte to an I2C master. More...
void address (int address)
 Set the I2C slave address. More...
void stop (void)
 Reset the I2C slave back into the known ready receiving state. More...

I2CSlave example

Try this example to see how an I2C responder works.

#include <mbed.h>

#if !DEVICE_I2CSLAVE
  #error [NOT_SUPPORTED] I2C Slave is not supported
#endif

I2CSlave slave(p9, p10);

int main() {
   char buf[10];
   char msg[] = "Slave!";

   slave.address(0xA0);
   while (1) {
       int i = slave.receive();
       switch (i) {
           case I2CSlave::ReadAddressed:
               slave.write(msg, strlen(msg) + 1); // Includes null char
               break;
           case I2CSlave::WriteGeneral:
               slave.read(buf, 10);
               printf("Read G: %s\n", buf);
               break;
           case I2CSlave::WriteAddressed:
               slave.read(buf, 10);
               printf("Read A: %s\n", buf);
               break;
       }
       for(int i = 0; i < 10; i++) buf[i] = 0;    // Clear buffer
   }
}
Important Information for this Arm website

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies. If you are not happy with the use of these cookies, please review our Cookie Policy to learn how they can be disabled. By disabling cookies, some features of the site will not work.