I2C maestro

Dependencies:   mbed

Revision:
0:b90c11323d98
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Tue Mar 07 11:35:15 2017 +0000
@@ -0,0 +1,52 @@
+/*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(p25); //red led
+DigitalOut green_led(p26); //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 <-- ojo con esto
+
+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  <-- ojo con esto
+        recd_val=i2c_port.read(addr); //Read and save the received byte
+        i2c_port.stop(); //force a stop condition
+        
+        //set leds according to incoming word 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;
+            }
+        }
+}
\ No newline at end of file