Reputation: 44739
I'm successfully reading bytes, as an I2C slave, using the STM32 HAL.
How can I tell how many bytes were received before the STOP?
I currently read the received data with an implementation of:
void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c) {
const uint8_t register_to_write = rx_buffer[0];
const uint8_t * rx_data = rx_buffer + 1;
...
}
Where I read from the rx_buffer
which I earlier gave to:
HAL_I2C_Slave_Seq_Receive_IT(&hi2c1, rx_buffer, RX_BUFFER_SIZE, I2C_FIRST_FRAME)
Upvotes: 0
Views: 1419
Reputation: 44739
An easier to access variable is XferCount
:
void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c)
{
const size_t size = RX_BUFFER_SIZE - 1 - hi2c->XferCount;
...
In my case, RX_BUFFER_SIZE == 33
and I see hi2c->XferCount == 28
after receiving the sub-address/register-number byte and four bytes of data.
Upvotes: 0
Reputation: 1525
I2C CR2 (control register 2) has, among other things, NBYTES field
where SBC is "Slave Byte Control", which is set in I2C CR1, specifics of what it is are of course in the I2C section of the reference manual.
It looks like NBYTES is programmed with the number of bytes you expect to receive before the transmission happens. So if you provide 10-byte buffer for HAL, I would expect to see 10 in NBYTES field before physical communication begins. Thus, if you receive fewer bytes, it would be reasonable to expect "leftover" value in NBYTES - how many bytes were yet to receive after communication ended (logic identical to DMA counter). So if your receive buffer was of length 10, but after communication, NBYTES is, say, 4, then you received 10-4=6 bytes of data. Of course, it's your job to check how exactly HAL sets NBYTES and whether it nullifies it at the end of reception. But yes, in principle, it's totally doable.
Upvotes: 1