Mbed – Test of i2c communication between master and slave

Connect GND, SDA,SCL lines of master and slave MCU. SDA and SCL are required pullup resistor.Mbed – Test of i2c communication between master and slave

I2C master : LPC1114
I2C slave :    LPC812 

Connect GND, SDA,SCL lines of master and slave MCU. SDA and SCL are required pullup resistor.

Code 

Master

#include “mbed.h”
#define slave_add ((uint8_t) 0xA0)
Serial device(dp16, dp15);  // tx, rx
I2C i2c(dp5, dp27);//sda,scl
int main() {
    Timer name;
    i2c.frequency(100000);
    char cmd[2];
    char data[15];
   
    while(1){
        cmd[0]=’0′;
        device.printf(“Request: %s ..”,cmd);
        i2c.write(slave_add, cmd, 1);
        i2c.read(slave_add,data, 5);
        device.printf(“Respond: %sn”,data);
        wait(1);
        cmd[0]=’1′;
       device.printf(“Request: %s ..”,cmd);
        i2c.write(slave_add, cmd, 1);
        i2c.read(slave_add,data, 5);
        device.printf(“Respond: %sn”,data);
        wait(1);
        cmd[0]=’5′;
       device.printf(“Request: %s ..”,cmd);
        i2c.write(slave_add, cmd, 1);
        i2c.read(slave_add,data, 6);
        device.printf(“Respond:%sn”,data);
        wait(1);
    }
}

Slave

#include <mbed.h>

I2CSlave slave(P0_10, P0_11);
int main() {
    char buf[2];
    uint8_t data;
    slave.address(0xA0);
    while (1) {
        int i = slave.receive();
        for(int i = 0; i < 2; i++) buf[i] = 0;
        switch (i) {
            case I2CSlave::ReadAddressed:
                if(data==0){
                    slave.write(“zero”,5);
                }
                else if(data==1){
                     slave.write(“once”,5);
                }
                else {
                    slave.write(“Error”,6);
                }
                break;
            case I2CSlave::WriteGeneral:
                break;
            case I2CSlave::WriteAddressed:
                slave.read(buf, 1);
                data=atoi(buf);
                break;
        }
    }
}

 

Sponsored Links: