cancel
Showing results for 
Search instead for 
Did you mean: 

How to send uint32_t hex via USART

yongjie989
Associate II
Posted on March 26, 2016 at 05:33

Hi All,

I would like to send uint32_t hex via USART, but no idea how to do it.

for example:

uint32_t buffer[2];

buffer[0] = 0x12345678;

buffer[1] = 0x87654321;

USART_puts(buffer[0])  <-- ????  the USART_puts length is uint8_t not 32-bit

void USART_puts(uint8_t * data){

    uint8_t u_i=0;

    while(data[u_i]!='\0')

    {

        USART_SendData(USART6, data[u_i++]);

        while(USART_GetFlagStatus(USART6, USART_FLAG_TXE) == RESET);          

    }

}

Thank you.

2 REPLIES 2
macgeorgio
Associate II
Posted on March 26, 2016 at 06:48

Hello,

in order to keep the USART_puts function as is (send 8bit characters), I propose you to create an intermediate function which will split the buffer of 32bit elements to a buffer of 8bit elements.

A simple function to do this would be:

void splitbuffer(uint32_t* buf32bit,uint8_t* buf8bit)

{

    int i;

    for (i=0;i<sizeof(buf32bit)/4;i++)

    {

        buf8bit[4*i+0]=(buf32bit[i]>>24)&0xFF;

        buf8bit[4*i+1]=(buf32bit[i]>>16)&0xFF;

        buf8bit[4*i+2]=(buf32bit[i]>>8)&0xFF;

        buf8bit[4*i+3]=(buf32bit[i])&0xFF;

    }

}

and you would call it by:

splitbuffer(buffer32bit,buffer8bit);

(remember to declare a buffer8bit[] array with four times the number of elements of buffer32bit.

How the function works is quite simple:

- The for loop runs for every element of the 32bit buffer after determining its size (sizeof returns the size of the 32bit buffer in bytes and each element is 4 bytes long).

- For every element a shifting is performed starting from the Most Significant Byte (>>24) with a bitwise AND to isolate the specific byte.

- The final 8bit buffer is little endian, meaning that the most significant byte is at the first position and the least significant byte is at the last position.

Posted on March 26, 2016 at 11:16

void USART_buffer(uint8_t * data, size_t size)
{
while(size--)
{
while(USART_GetFlagStatus(USART6, USART_FLAG_TXE) == RESET);// Check it is empty FIRST 
USART_SendData(USART6, *data++);
}
}
USART_buffer((void *)buffer, sizeof(buffer));
USART_puts(buffer[0]); // INCORRECT, buffer[0] is NOT a pointer

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..