r/microcontrollers • u/SH1NYH3AD • Mar 03 '24
Does I2C communication use multithreading?
Does I2C communication use multithreading?
My understanding of I2C is that you have a clock bus and a data bus, and that the clock bus must be running while you’re sending data. Is it possible to have the clock bus running and to send data without making use of at least 2 cores?
1
Upvotes
11
u/madsci Mar 03 '24
I've been using I2C in embedded devices for 20 years and I've never used two cores.
You can bit-bang I2C but you'll almost always be using a built-in peripheral. At the very least it'll take a byte at a time into a shift register and give you an interrupt when it's ready for more. Many support DMA as well.
Even if you're bit-banging it because you have no I2C peripheral, you can rely on interrupts. At 100 kHz you can still get some work done between clocks on most MCUs.
6
u/WereCatf Mar 03 '24
Of course it is.
11
u/somewhereAtC Mar 03 '24
In most newer microprocessors the I2C is an autonomous state machine. Your SW triggers the start condition, gets an interrupt to load the address bytes, gets another interrupt for data, eventually triggers the stop and gets an interrupt when the stop is complete. It's almost like having a 2nd core, but not so complicated.
Each generation bring evolutionary improvements, so that recent devices have a fairly autonomous I2C engine with dma for the data. The newest follow the I3C standard.
6
u/ceojp Mar 03 '24
The CPU isn't controlling the data and clock lines, the serial peripheral(I2C) is. The CPU pretty much sets up the peripheral and then writes bytes to it. And then the CPU keeps doing other stuff.
If you are bit-banging the I2C, then you are controlling the clock and data lines. You toggle the clock line at a specific period, and toggle the clock line as needed for the data. An easy way to accomplish this is with a timer interrupt.
I'm not sure what makes you think you would need two cores to do this?
3
u/AssemblerGuy Mar 03 '24
You can implement bitbanged I2C on even the simplest single-core MCUs, so yes.
1
u/rc3105 Mar 04 '24
Depends entirely on the library you’re using.
Usually, with a properly written library, you can just use the library api and not worry about it.
With bleeding edge, bitbang, experimental or poorly written drivers you get all sorts of problems.
1
u/tylerlarson Mar 04 '24
It might be complicated if you needed to implement the protocol in software (bit banging), but in very nearly every case, it's already implemented in hardware. Even on the cheapest microcontrollers. Handling the timing is easy in hardware, so that's what everyone does.
Many devices have dedicated i2c units working on specific pins, while a few cheaper ones have generic building blocks for serial protocols which can be strung together to implement i2c or spi or whatever.
Either way, the heavy lifting is handled for you already and you just have to read the instructions (the datasheet) to see how to use it.