I2CMaster Example

Dependencies:   mbed

Files at this revision

API Documentation at this revision

Comitter:
Kit1
Date:
Thu Aug 29 15:01:37 2013 +0000
Commit message:
I2C Master working

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r b4dab7bb911f main.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Thu Aug 29 15:01:37 2013 +0000
@@ -0,0 +1,45 @@
+/*Program Example 7.5: I2C Master, transfers switch state to second mbed acting as slave, and
+displays state of slave’ s switches on its leds.
+*/
+#include "mbed.h"
+I2C i2c_port(p9, p10); //Configure a serial port, pins 9 and 10 are sda, scl
+DigitalOut red_led(LED1); //red led
+DigitalOut green_led(LED2); //green led
+DigitalIn switch_ip1(p5); //input switch
+DigitalIn switch_ip2(p6);
+char switch_word ; //word we will send
+char recd_val; //value received from slave
+const int addr = 0x52; //the I2C slave address, an arbitrary even number
+
+int main() {
+    while(1) {
+        switch_word=0xa0; //set up a recognizable output pattern
+        if (switch_ip1==1)
+            switch_word=switch_word|0x01; //OR in lsb
+        if (switch_ip2==1)
+            switch_word=switch_word|0x02; //OR in next lsb
+        //send a single byte of data, in correct I2C package
+        i2c_port.start(); //force a start condition
+        i2c_port.write(addr); //send the address
+        i2c_port.write(switch_word); //send one byte of data, ie switch_word
+        i2c_port.stop(); //force a stop condition
+        wait(0.002);
+        //receive a single byte of data, in correct I2C package
+        i2c_port.start();
+        i2c_port.write(addr|0x01); //send address, with R/W bit set to Read
+        recd_val=i2c_port.read(addr); //Read and save the received byte
+        i2c_port.stop(); //force a stop condition
+        //set leds according to word received from slave
+        red_led=0; //preset both to 0
+        green_led=0;
+        recd_val=recd_val&0x03; //AND out unwanted bits
+        if (recd_val==1)
+            red_led=1;
+        if (recd_val==2)
+            green_led=1;
+        if (recd_val==3){
+            red_led=1;
+            green_led=1;
+        }
+    }
+}
diff -r 000000000000 -r b4dab7bb911f mbed.bld
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Thu Aug 29 15:01:37 2013 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed/builds/9c8f0e3462fb
\ No newline at end of file