前面已经介绍很多4G连网流程了操作,包括每一条AT指令的作用和参数含义,相信大家已经很熟了,下面我们根据实际测试的结果贴出代码(C语言):
操作环境:linux系统
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
char *AT_CFUN_1 = "AT+CFUN=1\r\n"; //定义开机AT指令
char *AT_COPS = "AT+COPS\?\r\n"; //定义查询注册网络的AT指令
char *AT_CGDATA = "AT+CGDATA=\"M-0000\", 1\r\n";//定义激活PS业务的AT指令
char *AT_CFUN_4 = "AT+CFUN=4\r\n"; //定义关机的AT指令
char *AT_DST = "AT^DSTMEX=1, 7\r\n"; //定义选择注册TD-LTE网络的AT指令
/*
*@brief write_com :写串口
*@param 1.fd 文件描述符 2.buf _w 分配的内存
*@return :void
*/
void write_com(int fd,char *buf_w)
{
int len=0;
int wr_num=strlen(buf_w);
tcflush(fd,TCIOFLUSH);
len=write(fd,buf_w,wr_num);
if(len!=wr_num)
{
perror("write Com fail");
exit(EXIT_FAILURE);
}
}
/*
*@brief read_com :读串口返回信息
*@param 1.fd 文件描述符 2.buf_r 分配的内存
*@return :void
*/
void read_com(int fd,char *buf_r)
{
int length=0;
memset(buf_r,0,255);
length=read(fd,buf_r,255);
int rd_num=strlen(buf_r);
if(length!=rd_num)
{
perror("Read Com fail");
exit(EXIT_FAILURE);
}
// printf("%s\n",buf_r);
}
int main(void)
{
char buffer[255];
int com_fd=open("/dev/ttyACM0",O_RDWR);
if(-1==com_fd)
{
perror("Can't Open Serial Port\n");
exit(EXIT_FAILURE);
}
config_com(com_fd); //初始化串口,设置数据位、停止位、奇偶校验位等的函数(在上一篇中讲过的)
memset(buffer,0,255);
write_com(comfd, AT_CFUN_4);
if(strstr(buffer,"OK\r\n")==NULL)
{
read_com(com_fd,buffer);
printf("%s\n",buffer);
}
write_com(com_fd,AT_CFUN_1);
printf("模块正在开机,请稍后.....\n");
sleep(5);
while(strstr(buffer,"+CEREG: 1\r\n")==NULL)
{
read_com(com_fd,buffer);
}
printf("模块开机成功!\n");
tcflush(com_fd, TCIOFLUSH);
write_com(com_fd, AT_COPS);
sleep(1);
printf("PC向模块发送:%s", AT_COPS);
char *sp;
while(( sp=strstr (buffer,"+COPS: ")) == NULL)
{
read_com(com_fd,buffer);
}
char *p[6];
int i=0;
char *ret=sp;
for(i = 0;(p[i] = strtok(ret, ",") )!= NULL;i++)
{
ret = NULL;
}
if(i>3)
{
if(*p[3]=='0')
{
printf("当前驻留网络为:GSM\n");
exit(0);
}
else if(*p[3] == '2')
{
printf("当前驻留网络为:TD-SCDMA\n");
exit(0);
}
else if(*p[3] == '7')
{
printf("当前驻留网络为:TD-LTE\n");
exit(0);
}
else
{
printf("当前驻留网络未知\n");
exit(0);
}
}
else
{
printf("注册网络失败!\n");
exit(0);
}
write_com(com_fd,AT_DST);
printf("PC向模块发送:%s", AT_DST);
while(strcmp(buffer, "OK\r\n") != 0)
{
read_com(comfd, buffer);
printf("%s", buffer);
}
sleep(1);
write_com(com_fd,AT_CGDATA);
printf("模块正在连接网络,请稍候...\n");
while(strstr(buffer,"CONNECT")==NULL)
{
read_com(com_fd,buffer);
}
printf("CONNECT SUCCESS!\n");
return com_fd;
}
这是最简单的连网程序,考虑的情况比较少,优化可以加入3G/2G网络的连网步骤,优先级顺序:4G>3G>2G.
有兴趣的可以继续完善。
连网流程了操作
是的,其实这只是最简单的范例,要做的好还需要加入网络切换和网络监测功能,有兴趣可以做做哈