I'm trying to write a program that communicates with serial port which is connected to GSM modem. Using AT command to communicate with modem. Here's my code. Got it from http://tldp.org/HOWTO/Serial-Programming-HOWTO/x115.html - Canonical Input Processing.
It works fine when output returns single line. For example:
AT
returns OK
And my problem is If i send AT+CPIN?
which returns several lines for example:
+CPIN: SIM PIN
OK
but my program reads only +CPIN: SIM PIN
and breaks.How to fix it ?
#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);
}
code UPDATE removed duplicate read