通过 UART 嵌入式应用程序将 ASCII 字符串转换为十六进制值

ASCII string to HEX value conversion over UART embedded Application

我正在从事一些嵌入式项目[PIC MCU],我将在其中通过 UART 接收数据。数据将包含一些我必须将其转换为 HEX 的 ascii 值,这些转换后的 HEX 值将进一步用于一些 operation.I 需要帮助 所以我的问题是任何人都有逻辑部分如何完成?不过,我已经做了一些工作……任何 Whosebug 线程、提示或 CODE 都将受到高度赞赏 到目前为止,这是我的代码

#include "mcc_generated_files/mcc.h"
#define _XTAL_FREQ 16000000
#define FRAMESIZE 18

void main(void)
{
   uint8_t data ,i,j;
   uint8_t value;
   uint8_t RX_Buffer [] ,RGB_data[] ,HEX_data[]   ;

    // initialize the device
    SYSTEM_Initialize();
    INTERRUPT_GlobalInterruptEnable();          // Enable the Global Interrupts
    INTERRUPT_PeripheralInterruptEnable();      // Enable the Peripheral Interrupts


    do
    {
        data = EUSART_Read();             // Read received character
        for (i = 0; i<FRAMESIZE ; i++)
        {
          RX_Buffer[i] = data;
        }

        EUSART_Write(data);               // Echo back the data received
        }while(!RCIF);        //check if any data is received

        // my UART data command starts with R and ends with '\n'
        if(RX_Buffer[0]=='R' && RX_Buffer[FRAMESIZE-1] == '\n')
        {
             LATAbits.LATA2   = 1;          //check flag
            __delay_ms(2000);
             LATAbits.LATA2   = 0;

            for (j = 0 ; j = 5; j++ )               // get the RGB value in separate array
            {
                RGB_data[j] = RX_Buffer[j+3];
                HEX_data[value] = RGB_data[j]/16 ;
              // so I am somewhat stuck how can I collect the UART data {for eg "RGBFF00A0AA" is my command which will be in ascii
               if (HEX_data[value] <=9)
                {
                   HEX_data[value] += '0';                    
                }
                else 
                {
                    HEX_data[value]=HEX_data[value]-10+'A';
                }

            }

        }

}

如果你有 stdio,将 ASCII 输入转换为 HEX 是微不足道的。

void AsciiToHex(char * src, char * dest)
{
  while(*src)
  {
    sprintf(dest + strlen(dest), " %02X", *src);
    src++;
  }
} 

编辑:

在小型微控制器(attiny、PIC 16F、8051 等)中,您将没有可用的 stdio...在这种情况下,您将需要更多的实践方法,例如以下代码:

void AsciiToHex(char * src, char * dest)
{
  char hex[] = "0123456789ABCDEF";
  while(*src)
    {
      char low, high;
      high = *src >> 4; // high nibble
      low = *src & 0x0f; // low nibble
      *dest = hex[high];
      dest++;
      *dest = hex[low];
      dest++;
      *dest = ' ';
      dest++;
      src++;
    }
  *dest = 0;
}