Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
6 years, 7 months ago.
Communication between 2 LPC1768 over I2C
Hello
I'm trying to connect two mbed lpc 1768 boards over I2C. One should act as the master, the other as the slave.
The master needs to count from 0 to 15 and send the count to the slave every second. The slave needs to display the received data on its 4 leds and store the recieved data + 1 in an internal variable. The master will then read the internal variable half a second after sending the data and will display it on a terminal.
This is what I did:
#include "mbed.h" // I2C master mbed I2C master(p28,p27); const int slave_addr = 0x64 ; int cnt = 0; int main() { char buf[1]; while(1) { if(cnt < 16) { master.write(slave_addr,(char*)cnt,1); // write data to slave cnt = cnt + 1 ; wait(0.5); // wait half a second after sending data to slave master.read(slave_addr,buf,1); printf("Data read from Slave: %d\n",buf[0]); wait(0.5); } } }
#include "mbed.h" // I2C slave mbed I2CSlave slave(p28,p27); BusOut myleds(LED1,LED2,LED3,LED4); const int slave_addr = 0x64; int cnt; int main() { slave.address(slave_addr); while(1) { int cmd = slave.receive(); switch(cmd){ case I2CSlave::WriteAddressed: cnt = slave.read(); myleds = cnt ; cnt = cnt + 1 ; break; case I2CSlave::ReadAddressed: slave.write(cnt); break; } cnt = 0 ; // clear cnt } }
In addition to the above, I have also connected two 300 ohm resistors to both SCL and SDA to 3.3v Yet it does not work the way it should.
I'd appreciate any help
Thank you
1 Answer
6 years, 7 months ago.
A value of 300 ohm for the pullup is too low. It should be around 2k7. Also make sure you have a common GND between the two mbed devices. That will be the case when both are connected to the same PC via a USB cable. Otherwise, use a separate wire to connect the GND pins. Note that the I2C slave software is tricky. It will crash the I2C engine when something goes wrong and you have to reset the mbed to try again. Resetting cnt inside the while(1) of the slave will result in a value of 0 being returned all the time.
In addition to the hardware modifications suggested by Wim try to modify also the code:
- In master's code take
cnt
's address for casting tochar*
as below:
Master
//master.write(slave_addr,(char*)cnt,1); // write data to slave master.write(slave_addr,(char*)&cnt,1); // write data to slave
- Try to modify slave's
while
loop as follows:
Slave
while(1) { int cmd = slave.receive(); switch(cmd){ case I2CSlave::WriteAddressed: //cnt = slave.read(); // This did not work for me on a NUCLEO board. slave.read((char*)&cnt, 1); myleds = cnt ; cnt = cnt + 1 ; break; case I2CSlave::ReadAddressed: slave.write(cnt); break; } //cnt = 0 ; // Don't clear cnt here to prevent sending a 0 back to the master. }