I've installed RPi.GPIO. It doesn't support I²C yet, but can I use it to bit bang I²C?
I would just need the Raspberry Pi to be the master.
I've installed RPi.GPIO. It doesn't support I²C yet, but can I use it to bit bang I²C?
I would just need the Raspberry Pi to be the master.
As one of the commenters pointed out, using a native/hardware I²C implementation is much preferred, as the produced I²C signals would be much nicer (read: compatible). The CPU load would be negligible as you do not have to busy wait to produce delays, and often faster (400 kHz is one standard speed).
However, bit-banging is useful sometimes, when you need to produce a particular signal pattern or when simply hardware I²C does not exist or or is not suitable for some reason. A nice example of bitbanging code can be found in the Wikipedia article I²C.
A simpler design, and preferred one, if performance is not the most critical, is to follow the algorithm from the Wikipedia article (and comments below). You need to pick two lines, one for SCL one for SDA, provide suitable pull-up resistors. Remember that idle line state is "high". You would configure the lines as "out" and toggle them any way you need. For polling the lines for ACK or clock stretch you should set them high, switch to "input" mode and then check the line state. The steps to produce start, stop and data states are in the Wikipedia link above.
If you need to get that last bit of performance out of your design, you can use four pins, SDA in
, SDA out
, SCL in
and SCL out
. The 'in' ones are permanently set to input and 'out' ones permanently set to output. This saves you the calls to switch pin modes.
[Edited to first offer simpler design as pointed out in the comments below.]
while (read_SCL() == 0) { // Clock stretching
– John La Rooy
Jul 21 '12 at 21:05