Rob Toulson / Mbed 2 deprecated PE_07-05_I2CMaster

Dependencies:   mbed

Committer:
robt
Date:
Mon Oct 15 21:25:53 2012 +0000
Revision:
0:addc96275da2
by Rob Toulson and Tim Wilmshurst from textbook "Fast and Effective Embedded Systems Design: Applying the ARM mbed"

Who changed what in which revision?

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