Y
Y
Yu Yu2018-08-14 20:19:59
Microcontrollers
Yu Yu, 2018-08-14 20:19:59

How can uint32_t be interpreted into uint8_t registers?

Greetings!
Program for STM32.
There are uint32_t variables in memory, you need to send the variables via UART whose register is uint8_t.
There are a couple of options:
1) Through the union

uint8_t transmitBuffer[32];
union {
  uint32_t var;
  uint8_t a_var[4];
} interprVar;

uint32_t temp = 0xFFFF;

interpVar.var = temp;

for (unsigned char i = 0; i < 4; i++)  {
    transmitBuffer[i] = interprVar.a_var[i];
}

2) Or through shifts:
transmitBuffer[0] = 0x000000FF & (temp >> 24);
transmitBuffer[1] = 0x000000FF & (temp >> 16);
transmitBuffer[2] = 0x000000FF & (temp >> 8);
transmitBuffer[3] = 0x000000FF & (temp);  
  
HAL_UART_Transmit_IT(&huart1, transmitBuffer, 4);

Through the index I'm afraid.
What jambs can await me?
Is there a better way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-08-14
@xztau

What jambs can await me?

Byte transfer order is different (big/little endian), in your two examples it is already different (given that STM32 is little endian by default).
From the point of view of the generated code, both proposed options are the same.
In terms of readability (and in the absence of endianness requirements), I would suggest the following:
void send_uint32(uint32_t v)
{
    uint8_t transmitBuffer[4];
    memcpy(transmitBuffer, &v, sizeof(v));
    HAL_UART_Transmit_IT(&huart1, transmitBuffer, sizeof(v));
}

If there are endianness requirements, I would choose shifts.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question