cancel
Showing results for 
Search instead for 
Did you mean: 

I2C Receive Function Size Parameter Problem

gunccc
Associate II

Hi,

I am working on STM32G474RET6 MCU in i2c slave mode. I want to make a polling mode with DMA but the problem is i don't know the receiving data's length. Every time it can be different. But 'HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)' function takes size parameter. I tried to give the size parameter buffer size. And for example i gave 20 as a parameter but get 5 byte data.When i do that, it takes the whole data to the buffer but hi2c state stays busy and it does get into ErrorCallback instead of RxCompltdCallback.

I tried to give the size 1 and takes the data one by one. It takes the data. But it overwrites the data in the same column of the buffer itself and in the end i can only take the last byte. And also again it goes into ErrorCallback.

Is there any way I can communicate without knowing the size parameter?

1 ACCEPTED SOLUTION

Accepted Solutions

If you are using the HAL libraries, that is the only way to deal with receiving an unknown number of bytes. And actually it makes sense (to me) as I'm not sure how else to handle that, even without HAL. You still need to start receiving into a buffer that is larger than any transfer you expect. And when the transfer ends, you need to check counters to see how many bytes you got. The only "strange" thing with HAL is doing that in an "error" handler. Think of it as an "exception" handler and maybe it won't seem so wrong.

View solution in original post

4 REPLIES 4
Bob S
Principal

I've done this with interrupt but not DMA. The solution is something like this:

  • Allocate your incoming data buffer to be larger than the largest transfer you can receive (as you tried with your 20 byte buffer)
  • Call Receive_DMA with that buffer and buffer size (as you tried)
  • In the error callback you can check the reason for the error and inspect the I2C_HandleTypeDef structure to see how many bytes were actually received (XferCount, XferSize and pBuffPtr)

Does this still work if the DMA is in cyclic mode ?

gunccc
Associate II

@S.Ma​  Yes its still work in circular mode.

@Bob S​ I've also tried to work in ErrorCallback like you said and yes its working. But i think it's not the proper way of communication. I was wondering if there is a right way to do it.

If you are using the HAL libraries, that is the only way to deal with receiving an unknown number of bytes. And actually it makes sense (to me) as I'm not sure how else to handle that, even without HAL. You still need to start receiving into a buffer that is larger than any transfer you expect. And when the transfer ends, you need to check counters to see how many bytes you got. The only "strange" thing with HAL is doing that in an "error" handler. Think of it as an "exception" handler and maybe it won't seem so wrong.