我正在开发一些嵌入式项目[PIC MCU],我将通过UART接收数据。数据将包含一些ascii值,我必须转换为HEX,那些转换后的HEX值将进一步用于某些操作我需要帮助 所以我的问题是,任何人都有逻辑部分如何做到这一点?我已经做了一些工作..任何stackoverflow线程,提示或CODE将是高度appreaciated 这是我的代码,直到现在
#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';
}
}
}
}
答案 0 :(得分:-1)
如果你有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;
}