实现功能
{0x00,0x00,0x30, 0x00, 0x00}—“0000300000”
搜索到的C语言程序
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
unsigned char port[5] = {0x00, 0x00, 0x30, 0x00, 0x00};
char buf[20] = {0};
sprintf(buf, "%02x%02x%02x%02x%02x", port[0], port[1], port[2], port[3], port[4]);
printf("十六进制:\t%s\n", buf);
}
运行结果
这里直接使用了sprintf,在VC编译器中运行是对的
问题:在keil编写源代码时,如何将结果显示在串口助手中?
在有串口的keil文件中加入这一段,见下
#include <string.h>
unsigned char port[5] = {0x00, 0x00, 0x30, 0x00, 0x00};
char buf[20];
void main(void)
{
P3M0 = 0X00;
P3M1 = 0X00;
P4M0 = 0X00;
P4M1 = 0X00;
P1M0 = 0X00;
P1M1 = 0X00;
P2M0 = 0X00;
P2M1 = 0X00;
Uart1_Init();
sprintf(buf, "%02x%02x%02x%02x%02x", port[0], port[1], port[2], port[3], port[4]);
uart1_printf(buf);
}
串口助手中:
错误!emmmm,继续百度,不行咱就Google
网上提供的代码看花了眼实在是太多了,到底哪个符合我的要求!!!???
再来一个!成功!
unsigned char unicode_number[22]={0x00,0x31,0x00,0x37,0x00,0x38,0x00,0x31,0x00,0x31,
0x00,0x30,0x00,0x30,0x00,0x30,0x00,0x39,0x00,0x32,0x00,0x37};
unsigned char consumer_number[100]={0};
/***********************************************************************
* 功能:将一个十六进制字节串转换成ASCII码表示的十六进制字符串
* 输入参数:pHex----十六进制数字节串首地址
* pAscii---转换后ASCII码表示的十六进制字符串首地址
* nLen---要转换的十六进制数长度(字节数)
* 注:转换后的结果全部是大写ASCII码表示的十六进制数
*此部分百度的
************************************************************************/
void HexToAscii(unsigned char *pHex, unsigned char *pAscii, int nLen)
{
unsigned char Nibble[2];
unsigned int i,j;
for (i = 0; i < nLen; i++){
Nibble[0] = (pHex[i] & 0xF0) >> 4;
Nibble[1] = pHex[i] & 0x0F;
for (j = 0; j < 2; j++){
if (Nibble[j] < 10){
Nibble[j] += 0x30;
}
else{
if (Nibble[j] < 16)
Nibble[j] = Nibble[j] - 10 + 'A';
}
*pAscii++ = Nibble[j];
} // for (int j = ...)
} // for (int i = ...)
}
void main(void)
{
//依旧用串口一进行实验
P3M0 = 0X00;
P3M1 = 0X00;
UART1_config(); //串口初始化
uart1_printf("UART1 is good! \r\n");
HexToAscii(unicode_number, consumer_number, 22);
uart1_printf(consumer_number);
while(1);
}
效果: