#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<termios.h>
#include<string.h>
typedef struct _tim
{
int hh;
int mm;
float ss;
}tim;
typedef struct _addr
{
int dd;
float mm;
char pos;
}addr;
typedef struct _date
{
int year;
int month;
int day;
}date;
int set_opt(int fd,int nSpeed, int nBits, char nEvent, int nStop)
{
struct termios newtio,oldtio;
if ( tcgetattr( fd,&oldtio) != 0) {
perror("SetupSerial 1");
return -1;
}
bzero( &newtio, sizeof( newtio ) );
newtio.c_cflag |= (CLOCAL | CREAD);
newtio.c_cflag &= ~CSIZE;
switch( nBits )
{
case 7:
newtio.c_cflag |= CS7;
break;
case 8:
newtio.c_cflag |= CS8;
break;
}
switch( nEvent )
{
case 'O':
newtio.c_cflag |= PARENB;
newtio.c_cflag |= PARODD;
newtio.c_iflag |= (INPCK | ISTRIP);
break;
case 'E':
newtio.c_iflag |= (INPCK | ISTRIP);
newtio.c_cflag |= PARENB;
newtio.c_cflag &= ~PARODD;
break;
case 'N':
newtio.c_cflag &= ~PARENB;
break;
}
switch( nSpeed )
{
case 2400:
cfsetispeed(&newtio, B2400);
cfsetospeed(&newtio, B2400);
break;
case 4800:
cfsetispeed(&newtio, B4800);
cfsetospeed(&newtio, B4800);
break;
case 9600:
cfsetispeed(&newtio, B9600);
cfsetospeed(&newtio, B9600);
break;
case 115200:
cfsetispeed(&newtio, B115200);
cfsetospeed(&newtio, B115200);
break;
case 460800:
cfsetispeed(&newtio, B460800);
cfsetospeed(&newtio, B460800);
break;
default:
cfsetispeed(&newtio, B9600);
cfsetospeed(&newtio, B9600);
break;
}
if( nStop == 1 )
newtio.c_cflag &= ~CSTOPB;
else if ( nStop == 2 )
newtio.c_cflag |= CSTOPB;
newtio.c_cc[VTIME] = 0;//重要
newtio.c_cc[VMIN] = 0;//返回的最小值 重要
tcflush(fd,TCIFLUSH);
if((tcsetattr(fd,TCSANOW,&newtio))!=0)
{
perror("com set error");
return -1;
}
// printf("set done!\n\r");
return 0;
}
void analyser(char buf[]);
int main(void)
{
int fd1,nset1,nread;
char buf[1024];
fd1 = open("/dev/ttyS1", O_RDWR|O_NOCTTY|O_NDELAY);//打开串口
if (fd1 == -1)
exit(1);
nset1 = set_opt(fd1,4800, 8, 'N', 1);//设置串口属性
if (nset1 == -1)
exit(1);
while (1)
{
memset(buf,0,1024);
nread = read(fd1, buf, 1024);//读串口
if (nread > 0){
// printf("\n GPS DATALen=%d\n",nread);
buf[nread] = '\0';
// printf( "GPS %s\n", buf); //输出所读数据
break;
}
sleep(2);//睡眠,等待数据多一点
}
close(fd1);
analyser(buf);
return 0;
}
void analyser(char buf[1024])
{
char *new_buf;
tim cur_time;
addr cur_lat;
addr cur_lng;
date cur_date;
float speed;
float heading;
char is;
new_buf = strstr(buf, "RMC");
new_buf += 4;
sscanf(new_buf, "%2d%2d%f,%c,%2d%f,%c,%3d%f,%c,%f,%f,%2d%2d%2d",\
&cur_time.hh,&cur_time.mm,&cur_time.ss,\
&is,\
&cur_lat.dd,&cur_lat.mm,&cur_lat.pos,\
&cur_lng.dd,&cur_lng.mm,&cur_lng.pos,\
&speed,&heading,\
&cur_date.day,&cur_date.month,&cur_date.year);
printf("当前时间:%d时%d分%.2f秒\n", cur_time.hh, cur_time.mm, cur_time.ss);
printf("当前位置:%s %d度%.4f分, %s %d度%.4f分\n", cur_lat.pos == 'N'?"北纬":"南纬", cur_lat.dd, cur_lat.mm\
,cur_lng.pos == 'E'?"东经":"西经", cur_lng.dd, cur_lng.mm);
printf("当前日期:20%d年%d月%d日\n", cur_date.year, cur_date.month, cur_date.day);
}