// this is a test about GPS Receiver
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h> // open() close()
#include <unistd.h> // read() write()
#include <termios.h> // set baud rate
#include <fcntl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#define DEVICE_TTYS "/dev/ttyS1"
//#define DEVICE_TTYS "/dev/ttyS0"
#define FUNC_RUN 0
#define FUNC_NOT_RUN 1
#define ORG_GPS 1
#define SEL_GPGGA 2
#define SEL_GPGLL 3
#define SEL_GPGSA 4
#define SEL_GPGSV 5
#define SEL_GPRMC 6
#define SEL_GPVTG 7
#define FUNC_QUIT 8
//------------------------------------- read datas from GPS -------------------------------------------------
// succese return 1
// error return 0
int read_GPS_datas(int fd, char *rcv_buf)
{
int retval;
fd_set rfds;
struct timeval tv;
int ret,pos;
tv.tv_sec = 1;
tv.tv_usec = 0;
pos = 0; // point to rceeive buf
while (1)
{
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
retval = select(fd+1 , &rfds, NULL, NULL, &tv);
if (retval == -1)
{
perror("select()");
break;
}
else if (retval)
{// pan duan shi fou hai you shu ju
ret = read(fd, rcv_buf+pos, 2048);
pos += ret;
if (rcv_buf[pos-2] == '\r' && rcv_buf[pos-1] == '\n')
{
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
retval = select(fd+1 , &rfds, NULL, NULL, &tv);
if (!retval) break;// if no datas, break
}
}
else
{
printf("No data\n");
break;
}
}
return 1;
} // end read_GPS_datas
//------------------------------------- FUNCTIONS ABOUT GPS -------------------------------------------------
//------------------------------------- FUNCTION 1 show all receive signal ----------------------------------
void GPS_original_signal(int fd)
{
char rcv_buf[2048];
while (1)
{
bzero(rcv_buf,sizeof(rcv_buf));
{
if (read_GPS_datas(fd,rcv_buf))
{
printf("%s",rcv_buf);
}
}
}
} // end GPS_original_sign
//------------------------------------- init seriel port ---------------------------------------------------
void init_ttyS(int fd)
{
struct termios newtio;
bzero(&newtio, sizeof(newtio));
newtio.c_lflag &= ~(ECHO | ICANON);
newtio.c_cflag = B4800 | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_oflag &= ~(OPOST);
newtio.c_cc[VTIME] = 5; /* inter-character timer unused */
newtio.c_cc[VMIN] = 0; /* blocking read until 9 chars received */
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
}//end init_ttyS
//------------------------------------- main ----------------------------------------------------------------
int main(void)
{
int fd;
// open seriel port
fd = open(DEVICE_TTYS, O_RDONLY);
if (fd == -1)
{
printf("open device %s error\n",DEVICE_TTYS);
}
else
{
printf("\t\tctrl + c to exit!\n");
init_ttyS(fd); // init device
GPS_original_signal(fd);
// close ttyS0
if (close(fd)!=0) printf("close device %s error",DEVICE_TTYS);
}
return 0;
} // end main