I'm successfully reading bytes, as an I²C 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)
I²C CR2 (control register 2) has, among other things, the NBYTES field:
Where SBC is "Slave Byte Control", which is set in the I²C CR1. Its specifics of what it is are of course in the I²C 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 a 10-byte buffer for HAL, I would expect to see 10 in the 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.