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


Use I2C Slave to communicate with I2C Master.

Synchronization level: not protected.

Note: Remember that you need a pull-up resistor on sda and scl. All drivers on the I2C bus are required to be open collector, and so it is necessary to use pull-up resistors on the two signals. A typical value for the pull-up resistors is around 2.2k ohms, connected between the pin and 3v3.

I2CSlave class reference

Note: The Arm Mbed API uses 8 bit addresses, so make sure to left-shift 7 bit addresses by 1 bit before passing them.

Public Member Functions
 I2CSlave (PinName sda, PinName scl)
 Create an I2C Slave interface, connected to the specified pins. More...
 I2CSlave (const i2c_pinmap_t &static_pinmap)
 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.

 * Copyright (c) 2006-2020 Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
#include <mbed.h>

#error [NOT_SUPPORTED] I2C Slave is not supported

I2CSlave slave(D14, D15);

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

    while (1) {
        int i = slave.receive();
        switch (i) {
            case I2CSlave::ReadAddressed:
                slave.write(msg, strlen(msg) + 1); // Includes null char
            case I2CSlave::WriteGeneral:
                slave.read(buf, 10);
                printf("Read G: %s\n", buf);
            case I2CSlave::WriteAddressed:
                slave.read(buf, 10);
                printf("Read A: %s\n", buf);
        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.