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.
10 years, 6 months ago.
doubt regarding i2c
sir, i saw your code , its working also.but i didn't get it..
#include "mbed.h" Serial pc(USBTX,USBRX); // Tx, Rx Pin, default boud = 9600 I2C i2c(p28, p27); // SDA, SCL int main() { char cmd[2]; // Command char echo[2]; // Echo result data (8bit) int addr = 0xA0; int addr1 = 0xA1; // Defalut I2C address of SRF08 int range = 0; // Rage data (16bit, cm) cmd[0] = 0x02; // Register(RangeValue) cmd[1] = 0x80; // (RangeValue*43)+43 = (69*43)+43 = 3010mm, maximum range i2c.write(addr,cmd,2); // Send I2C data (8bit*2) cmd[0] = 0x00; // Register(Command) cmd[1] = 0x51; // Ranging mode - Result in centimeters i2c.write(addr,cmd,2); // Send I2C data (8bit*2) wait(0.07); // Wait 70ms cmd[0] = 0x02; // Register(1st Echo) i2c.write(addr,cmd,1); // Send I2C data (8bit*1) i2c.read(addr1,echo,3); // Read I2C data (8bit*2) range = (echo[0]<<8)+echo[1]; // 8bit+8bit=16bit pc.printf("Range : %d cm\n",echo[0]); pc.printf("Range : %d cm\n",echo[1]); }
I dont know basics.. could u guide me please? i am using AT24C08A EEPROM with LPC11U24 using I2C , but why for this many cmd[]? pls explain me.
Question relating to:
1 Answer
10 years, 6 months ago.
For i2c to work you have to supply several bits of data. The read/write address of the device, the address of the register you wish read or write and if required the data to write to that register.
From the code you posted you can see that the 8-bit device write address is defined in the line:
int addr = 0xA0;
and the read address is defined underneath it
int addr1 = 0xA1;
next the code loads the cmd[] array with the commands to carry out, in this case writing a 0x80 to register 0x02.
cmd[0] = 0x02; cmd[1] = 0x80;
The code then calls the i2c.write() function to write the data to the bus.
i2c.write(addr,cmd,2);
the addr is the write address for the device. The cmd is the list of commands we have previously prepared, and the 2 indicates the number of commands we are sending.
To read a value from a device on the bus is slightly different. The first thing to do is send the device the address of the register we want to read. This is done is a similar way to writing data.
cmd[0] = 0x02; i2c.write(addr,cmd,1);
The 1 at the end of the i2c.write call indicates that this time we are only sending one command to the device. Now we can put the mbed into i2c read mode. This is done with the following command.
i2c.read(addr1,echo,3);
This function uses addr1, the read address of the device. The function is going to place 3 bytes of data into the echo array.
I hope that helps to explain the basics to you! You can find more information in the datasheet for the AT24C08A.