嵌入式linux编程过成中用到zigbee模块
zigbee从串口读数需要特定的字符段并且需要每两位字符数组元素转换成一个16进制数
(提取特定字符串+字符串转16进制)
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#include<string.h>
int serchzig(char *rdbuf,unsigned char *wtbuf)
{
char *beginbuf = NULL;
char *endbuf = NULL;
char midbuf[100]={0};
char str[4]={0};
//将主函数传入的buffer数组中fe~ff提取到midbuf中
beginbuf = strstr(rdbuf,"fe");
endbuf = strstr(rdbuf,"ff");
if(beginbuf == NULL || endbuf == NULL || beginbuf > endbuf)
{
printf("not found zigbee cmd!\n");
}
else
{
endbuf += strlen("ff");
strncpy(midbuf,beginbuf,endbuf-beginbuf);
}
printf("%s\n",midbuf);
//将midbuf中的字符每两个数组元素(即两个字符)转换为一个16进制数,并存入wtbuf[i]中。
int len = strlen(midbuf);
printf("%d\n",len);
//midbuf[len+1]='\0';
//printf("%d\n",len);
memset(str,0,sizeof(str));
int i = 0;
int j = 0;
for(j=0;j < len;j += 2)
{
strncpy(str,midbuf+j,2);
//memcpy(str,midbuf+j,2);
printf("str = %s\t",str);
wtbuf[i] = strtol(str,NULL,16);
printf("wtbuf[i] = 0x%02x\t i= %d\n",wtbuf[i],i);
memset(str,0,sizeof(str));
i++;
}
return 0;
}
int main()
{
char buffer[100]={"hellow zigbee fe1985ffdf"};//定义一个字符数组,并赋值
unsigned char zigbee[100]={0};//无符号数组/也可定义为char,否则打印可能出现6个f,是printf补码的问题,
//char *beginbuf = NULL;
//char *endbuf = NULL;
//char buff[100] = {0};
serchzig(buffer,zigbee);//调用函数,输出的zigbee数组已经是转换好的数组
printf("%s\n",zigbee);
printf("%x\n",zigbee[0]);
printf("%x\n",zigbee[1]);
printf("%x\n",zigbee[2]);
printf("%x\n",zigbee[3]);
printf("%x\n",zigbee[4]);
return 0;
}
运行结果:vc运行的。arm-linux还结合了串口,程序不能通用就用vc专门编写了一个例子
来源:oschina
链接:https://my.oschina.net/u/4392850/blog/4429732