#include <mbed.h>
#include <mbed_wait_api.h>
#include <string.h>
#define BUILD_I2C_SLAVE 1
#define SLAVE_ADDR 0xA0
#define BUFFER_SIZE 6
#if BUILD_I2C_SLAVE
#if !DEVICE_I2CSLAVE
#error [NOT_SUPPORTED] I2C Slave is not supported
#endif
int main() {
char buf[BUFFER_SIZE] = "ABCDE";
slave.address(SLAVE_ADDR);
while (1) {
int i = slave.receive();
switch (i) {
case I2CSlave::ReadAddressed:
slave.write(buf, BUFFER_SIZE);
printf("Written to master (addressed): %s\n", buf);
break;
case I2CSlave::WriteGeneral:
slave.read(buf, BUFFER_SIZE);
printf("Read from master (general): %s\n", buf);
break;
case I2CSlave::WriteAddressed:
slave.read(buf, BUFFER_SIZE);
printf("Read from master (addressed): %s\n", buf);
break;
}
}
}
#else
I2C master(I2C_SDA, I2C_SCL);
static const char* to_send[] = { "abcde", "12345", "EFGHI" };
int main() {
char buf[BUFFER_SIZE];
int send_index = 0;
while (1) {
strcpy(buf, to_send[send_index]);
if (master.write(SLAVE_ADDR, buf, BUFFER_SIZE)) {
printf("Failed to write to slave!\n");
} else {
printf("Written to slave: %s\n", buf);
}
if (master.read(SLAVE_ADDR, buf, BUFFER_SIZE)) {
printf("Failed to read from slave!\n");
} else {
printf("Read from slave: %s\n", buf);
}
send_index++;
if (send_index > 2) {
send_index = 0;
}
}
}
#endif
An I2C Slave, used for communicating with an I2C Master device.