|I2C Source Code For Microcontrollers|
|Written by Administrator|
|Sunday, 17 May 2009 01:40|
The Software for Minimal I2C
Are you an I2C noob? If so, check out this article before trying to port the source code.
Before we actually get into the software, these diagrams show how the bus is hooked up to the CPU.
If the CPU has the capability of driving open collector output lines and reading their state directly, then the I2C hardware connection couldn't be easier. The 5k pullup resistors make the two bus lines float high if no device on the bus is pulling them low. There is a tradeoff between the resistor value and the capacitance load on the lines. If the resistance is too high, then more devices on the bus tend to increase capacitance, and the signals are less square, leading eventually to failures. If the resistance is too low, then the weakest devices on the bus will not be able to sink enough current to drive the lines to logical 0.
If open collector lines are not available, it would be possible to use 2 outputs, and 2 input lines to accomplish the same thing. The diodes simply prevent the Out0 and Out1 output lines from driving the I2C lines high.
C - language Source code for Minimal I2C
The following source code is an example of a minimal I2C implementation. It was actually translated from FORTH, so this may contain some small mistakes.
The following bits are implementation-dependent code, which will vary depending on which CPU is being used.
#define SCLOUT( val ) set_p0_state( val ) /* CPU Dependent function to set p0 to low-state val=0, or float val=1 */
The first software step is to initialize the io ports to be open collector outputs, and then put the bus into an idle state. An idle state is where both lines are high. It may also be a good idea to generate a STOP condition on the bus before putting it idle.
I2C Start and Stop Conditions
The following code implements the I2C Start and Stop conditions using the primitives defined above.
Next - More I2c Source Code
|Last Updated on Sunday, 17 May 2009 13:52|