Home > Mobile >  How to save only certain bytes I need instead of all in an array?
How to save only certain bytes I need instead of all in an array?

Time:10-19

I am getting from a sensor via UART communication every second 10 bytes. But I don't need all bytes, actually only certain bytes to work with. Now what I do is to save all bytes into an array and create two new uint8_t's and assign them the byte from the buffer array I need.

Is there a way to only receive and save the bytes I need in the first place instead of all 10?

uint8_t buffer[10];

HAL_UART_Receive_DMA(&huart4, (uint8_t*)buffer, 10)

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart4)
{
  uint8_t value1 = buffer[4];
  uint8_t value2 = buffer[5];
  .
  .
  .
}

CodePudding user response:

In DMA mode you need to provide the full size buffer. There is no other way as reception is not controlled by the core (it is done ion the background) and the DMA controller signals end (ad if you want half and error conditions) of the transaction only

CodePudding user response:

Just get a pointer to simplify the buffer code.

uint16_t * value = (uint16_t *) &buffer[4];

But on the unneeded bytes with DMA on receiving and a UART you are out of options. All received bytes must be read out of the UART else there is stale data stuck in the UART FIFO.

However you could hide some of the ugliness in a function:

// Explanation of why we only need certain bytes.
uint16_t get_important_rx_data(void)
{
  return (uint16_t *) &buffer[4];
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart4)
{
  uint16_t * value = get_important_rx_data();
  .
  .
  .
}

This will also provide some abstraction from the message format to your code.

  • Related