⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 serial.c.txt

📁 C编写的GPS接受代码
💻 TXT
字号:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <stdlib.h>
#include "serial.h"
//some define
#define UInt32     unsigned int
#define Int16      short
#define UInt16     unsigned short
#define UInt8      unsigned char
#define Boolean    int
#define false      0
#define true       1
#define DEBUG
#ifdef DEBUG
#define TRACE(str, args...) printf(str, ## args)
#else
#define TRACE(str, args...)
#endif

#define GPS_RECV_CMD_MAX_BUF 128 //the buffer size
#define RMC_MAX_BUF 16 //the buffer size of rmc field
#if ! defined( CARRIAGE_RETURN )
#define CARRIAGE_RETURN 0x0D
#endif
#if ! defined( LINE_FEED )
#define LINE_FEED       0x0A
#endif
//the rmc info struct
typedef struct RMCINFO{
 int    bIsGPRMC;                 
 UInt8  hour, bjhour, min, sec, secFrac; 
 double latitude;                
 UInt8  latNS;                  
 double longitude;              
 UInt8  lgtEW;                
 UInt8  date, day, month, year; 
 double course;
 double speed;
}RMCINFO;
 
char buffer[GPS_RECV_CMD_MAX_BUF] = "GPRMC,161229.487,A,3723.2475,N,12158.3416,W,0.13,309.62,120598,,*10"; 

double FieldDouble( int field_number ); 
int main(void)
{
 int fd;
 int i;
 RMCINFO rmcinfo;
 char Latitude[RMC_MAX_BUF];
 char Longitude[RMC_MAX_BUF];
 char Degree[4];
 char Minute[8];
 char Time[RMC_MAX_BUF];
 char Hour[4];
 char Minu[4];
 char Second[4];
 char Date[RMC_MAX_BUF];
 char Day[4];
 char Month[4];
 char Year[4];
 
 int no = 0;
 

 //open the COM
 if((fd=open_port(fd,1))<0)
 {
  perror("open_port error");
  return;
 }
 TRACE("fd=%d\n",fd);
 
 //set the COM
 if((i=set_opt(fd,9600,8,'N',1))<0)
 {
  perror("set_opt error");
  return;
 }   
 
 
 // 
 while(1)
 {
  while(!Is_startGP(fd));
  TRACE("start to receive\n");

  //receive the info
  for(i = 0; i<GPS_RECV_CMD_MAX_BUF;i++) 
  {
   read(fd,&buffer[i],1);
   TRACE("%c",buffer[i]);
   if(buffer[i]=='\n')break;
  }
  TRACE("\n");

  //proc the RMC info
  if( (Is_RMC(buffer)) && (IsValid(2)) )
  {

   /*
    ** First we check the checksum...
    */
   Boolean check = IsChecksumBad( 12 );
   if ( check == true )
   {
    printf( "Invalid Checksum" );
    continue;
   }
   TRACE("Valid checksum\n");
   rmcinfo.bIsGPRMC = 1;
 
   //Time:6-15
   memset(Time, 0, RMC_MAX_BUF);
   Field(1, Time);
   TRACE("Time= %s\n",Time);
   for(i = 0;i < 4;i++)
    Hour[i]=0;
   Hour[0]=Time[0];
   Hour[1]=Time[1];

   for(i = 0;i < 4;i++)
    Minu[i]=0;
   Minu[0]=Time[2];
   Minu[1]=Time[3];
   for(i = 0;i < 4;i++)
    Second[i]=0;
   Second[0]=Time[4];
   Second[1]=Time[5];
   rmcinfo.hour = atoi(Hour);
   rmcinfo.min = atoi(Minu);
   rmcinfo.sec = atoi(Second);
   rmcinfo.secFrac = 0;
   rmcinfo.bjhour = rmcinfo.hour + 8;
   if(rmcinfo.bjhour >= 24)
    rmcinfo.bjhour -=  24;

   //Latitude:19-27
   memset(Latitude, 0, RMC_MAX_BUF);
   Field(3, Latitude);
   TRACE("Latitude= %s\n",Latitude);
   for(i = 0;i < 4;i++)
    Degree[i]=0;
   Degree[0]=Latitude[0];
   Degree[1]=Latitude[1];
   no = 2;
   for(i=0;i<8;i++)
    Minute[i]=0;
   for(i=0;i<7;i++)
    Minute[i]=Latitude[no+i];
   rmcinfo.latitude=(atof(Minute)) / 60.0 + atoi(Degree);

   //NS:29
   Field(4, &rmcinfo.latNS );

   //Longitude:31-40
   memset(Longitude, 0, RMC_MAX_BUF);
   Field(5, Longitude);
   TRACE("Longitude= %s\n",Longitude);
   for(i=0;i<4;i++)
    Degree[i]=0;
   Degree[0]=Longitude[0];
   Degree[1]=Longitude[1];
   Degree[2]=Longitude[2];
   no=3;
   for(i=0;i<8;i++)    
    Minute[i]=0;
   for(i=0;i<7;i++)
    Minute[i]=Longitude[no+i];
   rmcinfo.longitude=(atof(Minute)) / 60.0 + atoi(Degree);
   //WE:42
   Field(6, &rmcinfo.lgtEW);

   //     speed:44
   rmcinfo.speed  = FieldDouble(7);
 

   //      course
   rmcinfo.course = FieldDouble(8);

   //Date:
   memset(Date, 0, RMC_MAX_BUF);
   Field(9, Date);
   TRACE("Date = %s\n",Date);

   for(i = 0;i < 4;i++)
    Day[i]=0;
   Day[0]=Date[0];
   Day[1]=Date[1];

   for(i = 0;i < 4;i++)
    Month[i]=0;
   Month[0]=Date[2];
   Month[1]=Date[3];
   for(i = 0;i < 4;i++)
    Year[i]=0;
   Year[0]=Date[4];
   Year[1]=Date[5];
   rmcinfo.day = atoi(Day);
   rmcinfo.month = atoi(Month);
   rmcinfo.year = atoi(Year);
   printf("UTC Time:%d h %d m %d s\n",rmcinfo.hour,rmcinfo.min,rmcinfo.sec);
   printf("BJ Time:%d h %d m %d s\n",rmcinfo.bjhour,rmcinfo.min,rmcinfo.sec); 
   printf("Date:%d y %d m %d d\n",rmcinfo.year,rmcinfo.month,rmcinfo.day);
   printf("Latitude:%c wei %f \n",rmcinfo.latNS,rmcinfo.latitude);
   printf("Longitude:%c jing %f \n",rmcinfo.lgtEW,rmcinfo.longitude);
   printf("Speed:%f \n",rmcinfo.speed);
   printf("Course:%f \n",rmcinfo.course);
   printf("\n");
  }//end  Is_RMC
  else continue;
  sleep(1);
 }//end while 1
 close(fd);
 return 0;
}//end main
 

/*
 ** RMC - Recommended Minimum Navigation Information
 **                                                            12
 **        1         2 3       4 5        6 7   8   9    10  11|
 **        |         | |       | |        | |   |   |    |   | |
 ** $--RMC,hhmmss.ss,A,llll.ll,a,yyyyy.yy,a,x.x,x.x,xxxx,x.x,a*hh<CR><LF>
 **
 ** Field Number: 
 **  1) UTC Time
 **  2) Status, V = Navigation receiver warning
 **  3) Latitude
 **  4) N or S
 **  5) Longitude
 **  6) E or W
 **  7) Speed over ground, knots
 **  8) Track made good, degrees true
 **  9) Date, ddmmyy
 ** 10) Magnetic Variation, degrees
 ** 11) E or W
 ** 12) Checksum
 */
 

int Is_startGP(int fp)
{
 int status=0;
 char cc;
 read(fp,&cc,1);
 if(cc == '$')status=1;
 return status;
}
 
int Is_RMC(char p[GPS_RECV_CMD_MAX_BUF])
{
 int status=0;
 if(p[2] == 'R' && p[3] == 'M' && p[4] == 'C')
  status=1;
 return status;
}

int Field( int desired_field_number, char rmc_field[] ) 
{
 char return_string[RMC_MAX_BUF];
 int i;
 int index                = 0; 
 int current_field_number = 0;
 int string_length        = 0;
 memset(return_string, 0, RMC_MAX_BUF);
 memset(rmc_field, 0, RMC_MAX_BUF);
 string_length = GPS_RECV_CMD_MAX_BUF;
 while( current_field_number < desired_field_number && index < string_length )
 {
  if ( buffer[ index ] == ',' || buffer[ index ] == '*' )
  {
   current_field_number++;
  }
  index++;
 }
 if ( current_field_number == desired_field_number )
 {
  i = 0;
  while( index < string_length    &&
    buffer[ index ] != ',' &&
    buffer[ index ] != '*' &&
    buffer[ index ] != 0x00 )
  {
   return_string[i] = buffer[ index ];
   index++;
   i++;
  }
 }
 for(index = 0; index < i; index++)
  rmc_field[index] = return_string[index];
 TRACE("rmc_field: %s \n",rmc_field);
 return 0;
}
 

char ComputeChecksum( void ) 
{
 char checksum_value = 0;
 int string_length = GPS_RECV_CMD_MAX_BUF;
 int index = 0; 
 while( index < string_length    && 
   buffer[ index ] != '*' && 
   buffer[ index ] != CARRIAGE_RETURN && 
   buffer[ index ] != LINE_FEED )
 {
  checksum_value ^= buffer[ index ];
  index++;
 }
 TRACE("checksum_value = %x\n",checksum_value);
 return( checksum_value );
}
 
 
int  HexValue( const char *hex_string )
{
 int  return_value = 0;
 sscanf( hex_string, "%x", (int *) &return_value );
 TRACE("hex_string = %s\n",hex_string);
 TRACE("return_value = %x\n",return_value);
 return( return_value );
}
 
 

Boolean IsChecksumBad( int checksum_field_number ) 
{
 /*
  ** Checksums are optional, return TRUE if an existing checksum is known to be bad
  */
 char  checksum_in_sentence[RMC_MAX_BUF] ;
 memset(checksum_in_sentence, 0, RMC_MAX_BUF);
 Field( checksum_field_number, checksum_in_sentence);
 TRACE("checksum_in_sentence = %s\n",checksum_in_sentence);
 if ( checksum_in_sentence == "" )
 {
  return( true );
 }
 if ( ComputeChecksum() != HexValue( checksum_in_sentence ) )
 {
  return( true );
 } 
 return( false );
}
 
Boolean IsValid( int field_number ) 
{
 char field_data[RMC_MAX_BUF];
 memset(field_data, 0, RMC_MAX_BUF);
 Field( field_number, field_data );
 TRACE("field_data = %s\n",field_data);
 if ( *field_data == 'A' )
 {
  return( true );
 }
 else
 {
  return( false );
 }
}
 

double FieldDouble( int field_number ) 
{
 double tmp;
 char field_data[RMC_MAX_BUF];
 memset(field_data, 0, RMC_MAX_BUF);
 Field( field_number, field_data );
 TRACE("field_data = %s\n",field_data);
 tmp =atof(field_data);
 TRACE("tmp = %f\n",tmp);
 return tmp;
}

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; 
        newtio.c_lflag |= (ICANON|ECHO|ECHOE|ISIG);  /*added by tuzhibo 07-7-2*/  
	newtio.c_oflag |= OPOST;  /*added by tuzhibo 07-7-2*/         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]  = 3;
	newtio.c_cc[VMIN] = 10;
	tcflush(fd,TCIFLUSH);
	if((tcsetattr(fd,TCSANOW,&newtio))!=0)
	{
		perror("com set error");
		return -1;
	}
	printf("set done!\n");
	return 0;
}

int open_port(int fd,int comport)
{
	char *dev[]={"/dev/ttyS0","/dev/ttyS1","/dev/ttyS2"};
	long  vdisable;
	if (comport==1)
	{	fd = open( "/dev/ttyS0", O_RDWR|O_NOCTTY|O_NDELAY);
		if (-1 == fd){
			perror("Can't Open Serial Port");
			return(-1);
		}
	}
	else if(comport==2)
	{	fd = open( "/dev/ttyS1", O_RDWR|O_NOCTTY|O_NDELAY);
		if (-1 == fd){
			perror("Can't Open Serial Port");
			return(-1);
		}
	}
	else if (comport==3)
	{
		fd = open( "/dev/ttyS2", O_RDWR|O_NOCTTY|O_NDELAY);
		if (-1 == fd){
			perror("Can't Open Serial Port");
			return(-1);
		}
	}
	if(fcntl(fd, F_SETFL, 0)<0)
		printf("fcntl failed!\n");
	else
		printf("fcntl=%d\n",fcntl(fd, F_SETFL,0));
	if(isatty(STDIN_FILENO)==0)
		printf("standard input is not a terminal device\n");
	else
		printf("isatty success!\n");
	printf("fd-open=%d\n",fd);
	return fd;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -