Search code examples
serial-porthexasciiuart

How to read hex values with read function on UART


I need some help with the serial port (UART) read function. I need to read in and display the hex value, but currently I'm reading in the ASCII values.

to send the hex over the UART I use

char data [] = {0xFF};
write(fd, data, sizeof(data));

which does the work well. But I have a problem with the reading in. I want to be able to read hex values and use the read values later.

Currently I'm reading with this function

read(fd, buffer, sizeof(buffer));

But as a result it displays me the ASCII values, I know I need to make some kind of conversion, but I have searched and was unsuccessful of finding how to do it.

Thanks in advance.


Solution

  • Code is likely reading the data OK, but need to use "%X" for subsequent display.
    For each byte:

    If recent compiler,

    printf("%02hhX", buffer[i]);
    

    otherwise

    printf("%02X", (unsigned char) buffer[i]);