gpt4 book ai didi

c - 通过 UART 嵌入式应用程序将 ASCII 字符串转换为 HEX 值

转载 作者:行者123 更新时间:2023-11-30 18:12:02 24 4
gpt4 key购买 nike

我正在开发一些嵌入式项目[PIC MCU],我将通过UART接收数据。数据将包含一些ascii值,我必须将其转换为十六进制,这些转换后的十六进制值将进一步用于某些操作.我需要帮助所以我的问题是有人知道如何做到这一点的逻辑部分吗?我已经做了一些工作..任何 stackoverflow 线程、提示或代码都会受到高度赞赏这是我到目前为止的代码

#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++;
}
}

编辑:

在小型微 Controller (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;
}

关于c - 通过 UART 嵌入式应用程序将 ASCII 字符串转换为 HEX 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41936100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com