Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
main.cpp
00001 /*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. 00002 */ 00003 #include "mbed.h" 00004 I2C i2c_port(p9, p10); //Configure a serial port, pins 9 and 10 are sda, scl 00005 DigitalOut red_led(p25); //red led 00006 DigitalOut green_led(p26); //green led 00007 DigitalIn switch_ip1(p5); //input switch 00008 DigitalIn switch_ip2(p6); 00009 00010 char switch_word ; //word we will send 00011 char recd_val; //value received from slave 00012 const int addr = 0x52; //the I2C slave address, an arbitrary even number 00013 00014 int main() { 00015 while(1) { 00016 switch_word=0xa0; //set up a recognisable output pattern 00017 if (switch_ip1==1) 00018 switch_word=switch_word|0x01; //OR in lsb 00019 if (switch_ip2==1) 00020 switch_word=switch_word|0x02; //OR in next lsb 00021 //send a single byte of data, in correct I2C package 00022 i2c_port.start(); //force a start condition 00023 i2c_port.write(addr); //send the address 00024 i2c_port.write(switch_word); //send one byte of data, ie switch_word 00025 i2c_port.stop(); //force a stop condition 00026 wait(0.002); 00027 //receive a single byte of data, in correct I2C package 00028 i2c_port.start(); 00029 i2c_port.write(addr|0x01); //send address, with R/W bit set to Read 00030 recd_val=i2c_port.read(addr); //Read and save the received byte 00031 i2c_port.stop(); //force a stop condition 00032 00033 //set leds according to incoming word from slave 00034 red_led=0; //preset both to 0 00035 green_led=0; 00036 recd_val=recd_val&0x03; //AND out unwanted bits 00037 if (recd_val==1) 00038 red_led=1; 00039 if (recd_val==2) 00040 green_led=1; 00041 if (recd_val==3){ 00042 red_led=1; 00043 green_led=1; 00044 } 00045 } 00046 }
Generated on Wed Jul 20 2022 12:43:42 by
1.7.2