reading serial port responce

Status
Not open for further replies.

Nathanb4u

Newbie level 1
Joined
Sep 16, 2009
Messages
1
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Location
USA
Activity points
1,303
read serialport response after write

Hi All,

I am new this GPRS. And i am using wavecom modem, I need to establish a gprs connection with server, i tried with minicom( in LINUX) using at commands. it is sending the data.

Now same thing i need to implement with C code.

After writing "AT\r" to serial port like write(fd,"at\r",3);

i need to read the OK/ERROR response to a buffer, and compare with reference.

here i was not able to capture OK responce to a buffer variable.

is it because of time delay to read the serial port.

kindly check the same.

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <termios.h>
#include <fcntl.h>
#include <sys/time.h>
#include <signal.h>

#define BAUD_RATE 115200

int main()
{

int fd;
long baud;
struct termios options;

/* open the port */
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
fcntl(fd, F_SETFL, 0);

if(fd < 0)
{
printf("\n fail to open serial port");
return 0;
}
else
{ printf("\n success in opening serial port\n"); }

/* get the current options */
tcgetattr(fd, &options);

switch(BAUD_RATE)
{
case 2400:
baud = B2400;
break;
case 9600:
baud = B9600;
break;
case 19200:
baud = B19200;
break;
case 38400:
baud = B38400;
break;
case 115200:
baud = B115200;
break;
default:
break;
} // end of switch

/* set raw input, 1 second timeout */
options.c_cflag |= (CLOCAL | CREAD);
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST;
options.c_cc[VMIN] = 1;
options.c_cc[VTIME] = 1;

tcflush(fd, TCIFLUSH); /* flush the buffer */

/* set the options */
tcsetattr(fd, TCSANOW, &options);

/* initializing modem */

init_modem(fd);
return 0;

} // end of main


int /* O - 0 = MODEM ok, -1 = MODEM bad */
init_modem(int fd) /* I - Serial port file */
{

char buffer[255]; /* Input buffer */
char *bufptr; /* Current char in buffer */
int nbytes = 0; /* Number of bytes read */
int tries; /* Number of tries so far */
int i;

/* send an AT command followed by a CR */
write(fd, "AT\r",3); // writinig to serial port
sleep(1); // delay to get response to serial port it is in sec
/* read characters into our string buffer until we get a CR or NL */

memset(buffer,'\0',sizeof(buffer));
i = 0;
while(nbytes <= 0)
{

nbytes = read(fd,buffer,sizeof(buffer));
printf("buffer:%s\n",buffer); // here i am expecting OK responce in buffer variable
if (strncmp(buffer, "OK", 2) == 0)
nbytes = 1;
else
nbytes = -1;
}

if (strncmp(buffer, "OK", 2) == 0)
return (0);

return -1;
}

thanks
nathan
 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…