【发布时间】:2015-04-13 13:02:21
【问题描述】:
我正在尝试编写一个与连接到 GSM 调制解调器的串行端口通信的程序。使用 AT 命令与调制解调器通信。这是我的代码。从http://tldp.org/HOWTO/Serial-Programming-HOWTO/x115.html 得到它 - 规范输入处理。
当输出返回单行时它工作正常。例如:
AT 返回OK
我的问题是如果我发送AT+CPIN?,它会返回几行,例如:+CPIN: SIM PINOK
但我的程序只读取+CPIN: SIM PIN 并且会中断。如何修复它?
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#define BAUDRATE B38400
#define dev "/dev/ttyUSB0"
#define _POSIX_SOURCE 1
#define FALSE 0
#define TRUE 1
volatile int STOP=FALSE;
main()
{
char pinn[20];
char buf[255];
int fd,res=0;
printf("%s\n", dev);
struct termios oldtio,newtio;
fd = open(dev, O_RDWR | O_NOCTTY );
if (fd <0) {perror(dev); exit(-1); }
bzero(&newtio, sizeof(newtio));
newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR | ICRNL;
newtio.c_oflag = 0;
newtio.c_lflag = ICANON;
newtio.c_cc[VMIN] = 1;
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
if (fd < 0)
{
printf("Error opening serial port\n");
exit(1);
}
while(1){
scanf("%s",pinn);
strcat(pinn,"\r");
if (write(fd, pinn, strlen(pinn)) < strlen(pinn)) printf("Write error - %s \n", strerror(errno));
pinn[strlen(pinn)-1]=0;
while(1){
res = read(fd,buf,255);
buf[res]=0;
buf[res-1]=0;
if (res>1&&NULL==strstr(buf,pinn)) break;
}
printf("\"%s\"\n", buf);
}
close(fd);
}
代码更新删除重复读取
【问题讨论】:
-
如果
read返回 0(EOF)或 -1(错误),您的代码将中断。
标签: c port at-command