The I2C interface provides I2C Master functionality.
This interface can be used for communication with a I2C devices, such as serial memories, sensors and other modules or integrated circuits.
Hello World!
Reading range data from the SRF05 Ultrasonic Range Finder
#include "mbed.h"
I2C i2c(p9, p10); // sda, scl
Serial pc(USBTX, USBRX); // tx, rx
const int addr = 0x70; // define the I2C Address
int main() {
char cmd[2];
while(1) {
cmd[0] = 0x0; // pointer to command register
cmd[1] = 0x51; // Start ranging, results in cm
i2c.write(addr, cmd, 2); // Send command string
wait(0.07); // Could also poll, 65ms is typical
// Set pointer to location 2 (first echo)
cmd[0] = 0x2;
i2c.write(addr, cmd, 1);
i2c.read(addr, cmd, 2); // read the two-byte echo result
// print the ranging data to the screen
float echo = 0.01 * ((cmd[0] << 8) + cmd[1]);
pc.printf("Range = %.2f\n", echo);
wait(0.1);
}
}
Warning
Remember, you will need a pull-up resistor on sda and scl.
All drivers on the I2C bus are required to be open collector, and so it is necessary for pull up resistors to be used on the two signals. A typical value for the pullup resistors is around 2.2k ohms, connected between the pin and 3v3.
API
| I2C | An I2C Master, used for communicating with I2C slave devices |
| Functions | |
| I2C | Create an I2C Master interface, connected to the specified pins |
| frequency | Set the frequency of the I2C interface |
| read | Read from an I2C slave |
| read | Read a single byte from the I2C bus |
| write | Write to an I2C slave |
| write | Write single byte out on the I2C bus |
| start | Creates a start condition on the I2C bus |
| stop | Creates a stop condition on the I2C bus |
Details
The I2C Interface can be used on mbed pins p9/p10 and p28/p27
The default frequency of the I2C interface is 100KHz.
I2C is a two wire serial protocol that allows an I2C Master exchange data with an I2C Slave. The I2C protocol support upto 127 devices per bus. The I2C interface can be used for writing data words out of the I2C port, returning the data recieved back from I2C slave. The I2C clock frequency can be configured.
References
Last modified 07 Dec 2010, by
Simon Ford

No tags
|
30 comments
Thanks for adding default freq Simon Lerche