개발자/라즈베리파이4

Raspberry Pi와 인터페이싱하는 GPS 모듈

지구빵집 2020. 11. 24. 10:19
반응형

 

 

Raspberry Pi와 인터페이싱하는 GPS 모듈 

 

GPS 소개

 

  • Global Positioning System(GPS)은 지구 상에 정확하게 그 위치를 결정하기 위해 지구 공간 및 지상 스테이션에서 위성들에 의해 전송된 신호를 사용한다.
  • 위성 및 지상국에서 전송 된 무선 주파수 신호는 GPS에 의해 수신됩니다.
  • GPS는 이러한 신호를 사용하여 정확한 위치를 결정합니다. GPS 자체는 정보를 전송할 필요가 없습니다.
  • 위성 및 지상국에서 수신 된 신호에는 신호가 전송된 시간의 타임스탬프가 포함됩니다. 신호가 전송된 시간과 신호가 수신된 시간의 차이를 계산합니다. 신호의 속도를 사용하여 위성과 GPS 수신기 사이의 거리는 속도와 시간을 사용한 거리에 대한 간단한 공식을 사용하여 결정할 수 있습니다.
  • 3 개 이상의 위성 정보를 사용하여 GPS의 정확한 위치를 삼각 측량 할 수 있습니다.
  • GPS 및 사용 방법에 대한 자세한 내용은 센서 및 모듈 섹션의 GPS 수신기 기초 항목을 참조하십시오 .
  • GPS 수신기 모듈은 UART 통신을 사용하여 컨트롤러 또는 PC 터미널과 통신합니다. Raspberry Pi에서 UART를 사용하기 전에이를 구성하고 활성화해야 합니다.
  • Raspberry Pi의 UART 및 사용 방법에 대한 자세한 내용은 Raspberry Pi 섹션의 Python 및 C를 사용한 Raspberry Pi UART 통신 항목을 참조하십시오.  

 

GPS 모듈 

 

인터페이스 다이어그램 - 연결도

 

Raspberry Pi와 인터페이싱하는 GPS 모듈

 

GPS 모듈을 Raspberry Pi와 인터페이스하고 GPS 정보를 추출해 보겠습니다. Python 및 C (WiringPi)를 사용하여 GPS 모듈을 Raspberry Pi에 연결할 수 있습니다. GPS 모듈을 연결하려면 위 그림과 같이 GPS 모듈을 Raspberry Pi에 연결합니다.

 

Python을 사용하여 GPS 모듈에서 수신 한 NMEA GPGGA 문자열에서 위도, 경도 및 시간 정보를 추출해 보겠습니다. 그리고 콘솔 (터미널)에 인쇄합니다. 이러한 위도와 경도를 사용하여 Google지도에서 현재 위치를 찾습니다.

 

Python 프로그램 

 

'''
GPS Interfacing with Raspberry Pi using Pyhton
http://www.electronicwings.com
'''
import serial               #import serial pacakge
from time import sleep
import webbrowser           #import package for opening link in browser
import sys                  #import system package

def GPS_Info():
    global NMEA_buff
    global lat_in_degrees
    global long_in_degrees
    nmea_time = []
    nmea_latitude = []
    nmea_longitude = []
    nmea_time = NMEA_buff[0]                    #extract time from GPGGA string
    nmea_latitude = NMEA_buff[1]                #extract latitude from GPGGA string
    nmea_longitude = NMEA_buff[3]               #extract longitude from GPGGA string
    
    print("NMEA Time: ", nmea_time,'\n')
    print ("NMEA Latitude:", nmea_latitude,"NMEA Longitude:", nmea_longitude,'\n')
    
    lat = float(nmea_latitude)                  #convert string into float for calculation
    longi = float(nmea_longitude)               #convertr string into float for calculation
    
    lat_in_degrees = convert_to_degrees(lat)    #get latitude in degree decimal format
    long_in_degrees = convert_to_degrees(longi) #get longitude in degree decimal format
    
#convert raw NMEA string into degree decimal format   
def convert_to_degrees(raw_value):
    decimal_value = raw_value/100.00
    degrees = int(decimal_value)
    mm_mmmm = (decimal_value - int(decimal_value))/0.6
    position = degrees + mm_mmmm
    position = "%.4f" %(position)
    return position
    


gpgga_info = "$GPGGA,"
ser = serial.Serial ("/dev/ttyS0")              #Open port with baud rate
GPGGA_buffer = 0
NMEA_buff = 0
lat_in_degrees = 0
long_in_degrees = 0

try:
    while True:
        received_data = (str)(ser.readline())                   #read NMEA string received
        GPGGA_data_available = received_data.find(gpgga_info)   #check for NMEA GPGGA string                 
        if (GPGGA_data_available>0):
            GPGGA_buffer = received_data.split("$GPGGA,",1)[1]  #store data coming after "$GPGGA," string 
            NMEA_buff = (GPGGA_buffer.split(','))               #store comma separated data in buffer
            GPS_Info()                                          #get time, latitude, longitude
 
            print("lat in degrees:", lat_in_degrees," long in degree: ", long_in_degrees, '\n')
            map_link = 'http://maps.google.com/?q=' + lat_in_degrees + ',' + long_in_degrees    #create link to plot location on Google map
            print("<<<<<<<<press ctrl+c to plot location on google maps>>>>>>\n")               #press ctrl+c to plot on map and exit 
            print("------------------------------------------------------------\n")
                        
except KeyboardInterrupt:
    webbrowser.open(map_link)        #open current position information in google map
    sys.exit(0)

 

 

Python 용 결과는 아래와 같습니다.

 

 

Google지도의 출력 위치 

 

Google지도에 위치를 표시하려면 Google지도의 URL 링크를 호출해야 합니다. 추출된 경도와 위도를 사용하여 Google지도를 열기 위해 다음 링크를 사용할 수 있습니다.

 

 

http://maps.google.com/?q= <latitude>, <longitude>

 

C 언어를 사용한 소스코드

 

  • NMEA GPGGA 문자열을 추출하여 출력 창에 인쇄합니다. 여기에서는 C로 작성된 WiringPi 라이브러리를 사용하여 GPS 모듈을 읽습니다.
  • WiringPi에 대한 자세한 내용은 Raspberry Pi에서 WiringPi 라이브러리 사용 방법을 참조하세요. 

 아래 National Marine Electronics Association (NMEA)에 대한 문서를 참고하십시오.

 

NMEA Reference Manual.pdf
0.64MB

 

/*
	GPS Interfacing with Raspberry Pi using C (WiringPi Library)
	http://www.electronicwings.com
*/

#include <stdio.h>
#include <string.h>
#include <errno.h>

#include <wiringPi.h>
#include <wiringSerial.h>

int main ()
{
  int serial_port; 
  char dat,buff[100],GGA_code[3];
  unsigned char IsitGGAstring=0;
  unsigned char GGA_index=0;
  unsigned char is_GGA_received_completely = 0;
  
  if ((serial_port = serialOpen ("/dev/ttyS0", 9600)) < 0)		/* open serial port */
  {
    fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ;
    return 1 ;
  }

  if (wiringPiSetup () == -1)							/* initializes wiringPi setup */
  {
    fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ;
    return 1 ;
  }

  while(1){
	  
		if(serialDataAvail (serial_port) )		/* check for any data available on serial port */
		  { 
			dat = serialGetchar(serial_port);		/* receive character serially */		
			if(dat == '$'){
				IsitGGAstring = 0;
				GGA_index = 0;
			}
			else if(IsitGGAstring ==1){
				buff[GGA_index++] = dat;
				if(dat=='\r')
					is_GGA_received_completely = 1;
				}
			else if(GGA_code[0]=='G' && GGA_code[1]=='G' && GGA_code[2]=='A'){
				IsitGGAstring = 1;
				GGA_code[0]= 0; 
				GGA_code[0]= 0;
				GGA_code[0]= 0;		
				}
			else{
				GGA_code[0] = GGA_code[1];
				GGA_code[1] = GGA_code[2];
				GGA_code[2] = dat;
				}
		  }
		if(is_GGA_received_completely==1){
			printf("GGA: %s",buff);
			is_GGA_received_completely = 0;
		}
	}
	return 0;
}

 

 

참고 : GPS 모듈을 Raspberry Pi 3와 인터페이스 할 때 UART 통신을 위해 /dev/ttyS0 직렬 포트를 사용했습니다. Raspberry Pi 2 및 이전 모델과 인터페이스 하는 사용자는 대신 /dev/ttyAMA0을 사용해야 합니다. 

 

출력 결과는 아래와 같습니다.

 

GPS 데이터

 

 

참고

1. 포스팅 참고 원문

2. 아래 첨부 문서는 GPS 기초에 대해 아주 잘 설명된 문서입니다. 참고하세요.

 

GPSBasics.pdf
1.50MB

 

 

 

GPS Receiver Module https://www.electronicwings.com/sensors-modules/gps-receiver-module

 

 

 

반응형