I2CMaster Example

Dependencies:   mbed

Committer:
Kit1
Date:
Thu Aug 29 15:01:37 2013 +0000
Revision:
0:b4dab7bb911f
I2C Master working

Who changed what in which revision?

UserRevisionLine numberNew contents of line
Kit1 0:b4dab7bb911f 1 /*Program Example 7.5: I2C Master, transfers switch state to second mbed acting as slave, and
Kit1 0:b4dab7bb911f 2 displays state of slave’ s switches on its leds.
Kit1 0:b4dab7bb911f 3 */
Kit1 0:b4dab7bb911f 4 #include "mbed.h"
Kit1 0:b4dab7bb911f 5 I2C i2c_port(p9, p10); //Configure a serial port, pins 9 and 10 are sda, scl
Kit1 0:b4dab7bb911f 6 DigitalOut red_led(LED1); //red led
Kit1 0:b4dab7bb911f 7 DigitalOut green_led(LED2); //green led
Kit1 0:b4dab7bb911f 8 DigitalIn switch_ip1(p5); //input switch
Kit1 0:b4dab7bb911f 9 DigitalIn switch_ip2(p6);
Kit1 0:b4dab7bb911f 10 char switch_word ; //word we will send
Kit1 0:b4dab7bb911f 11 char recd_val; //value received from slave
Kit1 0:b4dab7bb911f 12 const int addr = 0x52; //the I2C slave address, an arbitrary even number
Kit1 0:b4dab7bb911f 13
Kit1 0:b4dab7bb911f 14 int main() {
Kit1 0:b4dab7bb911f 15 while(1) {
Kit1 0:b4dab7bb911f 16 switch_word=0xa0; //set up a recognizable output pattern
Kit1 0:b4dab7bb911f 17 if (switch_ip1==1)
Kit1 0:b4dab7bb911f 18 switch_word=switch_word|0x01; //OR in lsb
Kit1 0:b4dab7bb911f 19 if (switch_ip2==1)
Kit1 0:b4dab7bb911f 20 switch_word=switch_word|0x02; //OR in next lsb
Kit1 0:b4dab7bb911f 21 //send a single byte of data, in correct I2C package
Kit1 0:b4dab7bb911f 22 i2c_port.start(); //force a start condition
Kit1 0:b4dab7bb911f 23 i2c_port.write(addr); //send the address
Kit1 0:b4dab7bb911f 24 i2c_port.write(switch_word); //send one byte of data, ie switch_word
Kit1 0:b4dab7bb911f 25 i2c_port.stop(); //force a stop condition
Kit1 0:b4dab7bb911f 26 wait(0.002);
Kit1 0:b4dab7bb911f 27 //receive a single byte of data, in correct I2C package
Kit1 0:b4dab7bb911f 28 i2c_port.start();
Kit1 0:b4dab7bb911f 29 i2c_port.write(addr|0x01); //send address, with R/W bit set to Read
Kit1 0:b4dab7bb911f 30 recd_val=i2c_port.read(addr); //Read and save the received byte
Kit1 0:b4dab7bb911f 31 i2c_port.stop(); //force a stop condition
Kit1 0:b4dab7bb911f 32 //set leds according to word received from slave
Kit1 0:b4dab7bb911f 33 red_led=0; //preset both to 0
Kit1 0:b4dab7bb911f 34 green_led=0;
Kit1 0:b4dab7bb911f 35 recd_val=recd_val&0x03; //AND out unwanted bits
Kit1 0:b4dab7bb911f 36 if (recd_val==1)
Kit1 0:b4dab7bb911f 37 red_led=1;
Kit1 0:b4dab7bb911f 38 if (recd_val==2)
Kit1 0:b4dab7bb911f 39 green_led=1;
Kit1 0:b4dab7bb911f 40 if (recd_val==3){
Kit1 0:b4dab7bb911f 41 red_led=1;
Kit1 0:b4dab7bb911f 42 green_led=1;
Kit1 0:b4dab7bb911f 43 }
Kit1 0:b4dab7bb911f 44 }
Kit1 0:b4dab7bb911f 45 }