티스토리 뷰

Iot

아두이노 -GPS 센서 (GY-NEO6MV2)

잉_민 2024. 4. 18. 23:32

https://arduinostuff.blogspot.com/2014/05/neo6mv2-gps-module-with-arduino-uno-how.html

 

NEO6MV2 GPS Module with Arduino Uno HOW-TO

Introduction Using the NEO6MV2 GPS Module with Arduino is pretty straightforward. This tutorial uses TinyGPS Library by Mikal Hart. The ...

arduinostuff.blogspot.com

소프트웨어

https://codingrun.com/100#google_vignette

여기에서 TinyGPS 라이브러리를 다운로드하세요:  https://github.com/mikalhart/TinyGPS/releases/tag/v13 .

예제 폴더에서 "test_with_gps_device.ino"를 엽니다.


이 모듈은 전송 속도 9600을 사용하므로 setup()에서 

ss.begin(4800) -> ss.begin(9600)

대체한다.

(아두이노 라이브러리에 있음.)

 

 

file -ex 예제를 사용해보자

 

#include <SoftwareSerial.h>

#include <TinyGPS.h>

/* This sample code demonstrates the normal use of a TinyGPS object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/

TinyGPS gps;
SoftwareSerial ss(4, 3);

static void smartdelay(unsigned long ms);
static void print_float(float val, float invalid, int len, int prec);
static void print_int(unsigned long val, unsigned long invalid, int len);
static void print_date(TinyGPS &gps);
static void print_str(const char *str, int len);

void setup()
{
  Serial.begin(115200);
  
  Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
  Serial.println("by Mikal Hart");
  Serial.println();
  Serial.println("Sats HDOP Latitude  Longitude  Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum");
  Serial.println("          (deg)     (deg)      Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail");
  Serial.println("-------------------------------------------------------------------------------------------------------------------------------------");

  ss.begin(4800);
}

void loop()
{
  float flat, flon;
  unsigned long age, date, time, chars = 0;
  unsigned short sentences = 0, failed = 0;
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;
  
  print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
  print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
  gps.f_get_position(&flat, &flon, &age);
  print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 10, 6);
  print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 11, 6);
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  print_date(gps);
  print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
  print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
  print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
  print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
  print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);

  gps.stats(&chars, &sentences, &failed);
  print_int(chars, 0xFFFFFFFF, 6);
  print_int(sentences, 0xFFFFFFFF, 10);
  print_int(failed, 0xFFFFFFFF, 9);
  Serial.println();
  
  smartdelay(1000);
}

static void smartdelay(unsigned long ms)
{
  unsigned long start = millis();
  do 
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

static void print_float(float val, float invalid, int len, int prec)
{
  if (val == invalid)
  {
    while (len-- > 1)
      Serial.print('*');
    Serial.print(' ');
  }
  else
  {
    Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1); // . and -
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i)
      Serial.print(' ');
  }
  smartdelay(0);
}

static void print_int(unsigned long val, unsigned long invalid, int len)
{
  char sz[32];
  if (val == invalid)
    strcpy(sz, "*******");
  else
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0) 
    sz[len-1] = ' ';
  Serial.print(sz);
  smartdelay(0);
}

static void print_date(TinyGPS &gps)
{
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned long age;
  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  if (age == TinyGPS::GPS_INVALID_AGE)
    Serial.print("********** ******** ");
  else
  {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ",
        month, day, year, hour, minute, second);
    Serial.print(sz);
  }
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  smartdelay(0);
}

static void print_str(const char *str, int len)
{
  int slen = strlen(str);
  for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
  smartdelay(0);
}

 

오류:Compilation error: SoftwareSerial.h: No such file or directory

#include <SoftwareSerial.h> 

#include <TinyGPS.h>

/* This sample code demonstrates the normal use of a TinyGPS object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/

아두이노 나노 33 IoT는 하드웨어 시리얼 포트가 하나뿐이라 SoftwareSerial 라이브러리 대신 다른 방법을 사용해야 합니다.

위 코드에서는 TinyGPS 라이브러리를 사용하는데, 이는 아두이노의 기본 시리얼 통신을 통해 GPS 모듈과 데이터를 주고받습니다.

아두이노 나노 33 IoT에서 GPS 모듈을 연결하려면 아래와 같이 하시면 됩니다:

GPS 모듈의 TX핀을 아두이노의 RX핀(D0)에 연결
GPS 모듈의 RX핀을 아두이노의 TX핀(D1)에 연결
GPS 모듈의 VCC를 3.3V에 연결
GPS 모듈의 GND를 GND에 연결

창 근처나 야외에서 사용

#include <TinyGPS.h>
#include <avr/pgmspace.h>

TinyGPS gps;

void setup()
{
  Serial.begin(9600);  // GPS 모듈과의 통신 속도에 맞게 조정
  
  Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
  Serial.println("by Mikal Hart");
  Serial.println();
  Serial.print("Sizeof(gpsobject) = "); Serial.println(sizeof(TinyGPS));
  Serial.println();

  Serial.println("Sats HDOP Latitude Longitude Fix  Date       Time       Date Alt     Course Speed Card  Distance Course Card  Chars Sentences Checksum");
  Serial.println("          (deg)    (deg)     Age                        Age  (m)     --- from GPS ----  ---- to London  ----  RX    RX        Fail");
  Serial.println("--------------------------------------------------------------------------------------------------------------------------------------");
}
static void smartdelay(unsigned long ms)
{
  unsigned long start = millis();
  do 
  {
    while (Serial.available())
    {
      char c = Serial.read();
      gps.encode(c);
    }
  } while (millis() - start < ms);
}
void loop()
{
  while (Serial.available())
  {
    char c = Serial.read();
    gps.encode(c);
  }
  
  gpsdump(gps);
}

static void gpsdump(TinyGPS &gps)
{
  float flat, flon;
  unsigned long age, date, time, chars = 0;
  unsigned short sentences = 0, failed = 0;
  static const float LONDON_LAT = 51.508131, LONDON_LON = -0.128002;
  
  print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
  print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
  gps.f_get_position(&flat, &flon, &age);
  print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 9, 5);
  print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 10, 5);
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);

  print_date(gps);

  print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 8, 2);
  print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
  print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
  print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0UL : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
  print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : TinyGPS::course_to(flat, flon, 51.508131, -0.128002), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);

  gps.stats(&chars, &sentences, &failed);
  print_int(chars, 0xFFFFFFFF, 6);
  print_int(sentences, 0xFFFFFFFF, 10);
  print_int(failed, 0xFFFFFFFF, 9);
  Serial.println();
}

static void print_int(unsigned long val, unsigned long invalid, int len)
{
  char sz[32];
  if (val == invalid)
    strcpy(sz, "*******");
  else
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0) 
    sz[len-1] = ' ';
  Serial.print(sz);
}

static void print_float(float val, float invalid, int len, int prec)
{
  char sz[32];
  if (val == invalid)
  {
    strcpy(sz, "*******");
    sz[len] = 0;
        if (len > 0) 
          sz[len-1] = ' ';
    for (int i=7; i<len; ++i)
        sz[i] = ' ';
    Serial.print(sz);
  }
  else
  {
    Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1);
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i)
      Serial.print(" ");
  }
}

static void print_date(TinyGPS &gps)
{
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned long age;
  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  if (age == TinyGPS::GPS_INVALID_AGE)
    Serial.print("*******    *******    ");
  else
  {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d   ",
        month, day, year, hour, minute, second);
    Serial.print(sz);
  }
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
}

static void print_str(const char *str, int len)
{
  int slen = strlen(str);
  for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
}

오류2

값이 0만 뜸.. 

 

(GPT)
Arduino 포럼 토론에서 확인된 것처럼 Arduino Nano 33 IoT는 실제로 Serial1 통신에 핀 D0(RX) 및 D1(TX)을 사용합니다. 이 설정은 하드웨어 UART를 통한 직렬 통신을 허용하여 GPS 모듈( Arduino 포럼 ) 과 같은 주변 장치와의 안정적인 데이터 교환 방법을 제공합니다 .

일부에서는 SoftwareSerial 라이브러리와 같은 소프트웨어 기반 솔루션을 사용하는 장치와의 통신을 위해 핀 5 및 6을 선택할 수도 있지만 SAMD21 마이크로 컨트롤러가 장착된 Nano 33 IoT를 사용하면 SERCOM(직렬 통신) 기능을 사용하여 추가 직렬 인터페이스를 구성할 수 있습니다. 이러한 유연성 덕분에 필요한 경우 핀 0과 1의 사전 정의된 Serial1에만 의존하지 않고도 다양한 핀에 추가 하드웨어 직렬 포트를 생성할 수 있습니다 . ( Arduino 포럼 )

여러 직렬 인터페이스가 필요한 프로젝트의 경우 또는 기본 Serial1 핀이 부적합하거나 이미 사용 중인 경우 SAMD21의 SERCOM 기능을 활용하여 새로운 직렬 포트를 다른 핀에 매핑할 수 있으므로 하드웨어 설계 및 기능에 상당한 다양성을 부여할 수 있습니다 .​ ( GitHub ) ​. Serial1에 핀 5와 6을 사용하거나 기본 D0과 D1을 사용하는 것 사이의 선택은 추가 직렬 인터페이스의 필요성과 장치 연결 레이아웃을 포함하여 프로젝트의 특정 요구 사항에 따라 달라질 수 있습니다.

핀아웃과 IoT 애플리케이션에 기능을 활용하는 방법을 포함하여 Arduino Nano 33 IoT에 대한 포괄적인 세부 정보는 Arduino 웹사이트와 사용자가 통찰력과 솔루션을 공유하는 커뮤니티 포럼에서 제공되는 공식 문서와 가이드를 참조하세요. ​( Arduino Docs ) ​( eTechnophiles ) ​.

된다.

https://github.com/mikalhart/TinyGPSPlus/releases/tag/v1.0.3a

 

Release v1.0.3a · mikalhart/TinyGPSPlus

Same as previous release, except version number corrected in TinyGPSPlus.h

github.com

배선

tx선을 5번에 연결

rx선을 6번에 연결

#include <Arduino.h>
#include "wiring_private.h" 
#include <TinyGPSPlus.h>

// Define the pins for the GPS module connection
static const int RXPin =5, TXPin = 6;
static const uint32_t GPSBaud = 9600;

// Create a TinyGPSPlus object
TinyGPSPlus gps;

// Setup for the new hardware serial port over SERCOM
Uart myGPS(&sercom0, RXPin, TXPin, SERCOM_RX_PAD_1, UART_TX_PAD_0);

void SERCOM0_Handler()
{
    myGPS.IrqHandler();
}

void setup()
{
  // Initialize Serial communication at 115200 baud
  Serial.begin(115200);
  
  // Initialize Serial1 communication at 9600 baud for the GPS module
  myGPS.begin(GPSBaud);
  
  // Assign pins to SERCOM functionality
  pinPeripheral(RXPin, PIO_SERCOM_ALT);
  pinPeripheral(TXPin, PIO_SERCOM_ALT);

  Serial.println(F("DeviceExample.ino"));
  Serial.println(F("A simple demonstration of TinyGPSPlus with an attached GPS module"));
  Serial.print(F("Testing TinyGPSPlus library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
}

void loop()
{
  // Display information every time a new sentence is correctly encoded.
  while (myGPS.available() > 0)
    if (gps.encode(myGPS.read()))
      displayInfo();

  // If no GPS data is detected after 5 seconds, display a warning.
  if (millis() > 5000 && gps.charsProcessed() < 10)
  {
    Serial.println(F("No GPS detected: check wiring."));
    while(true);
  }
}

void displayInfo()
{
  Serial.println(F("google map link below:")); 
  if (gps.location.isValid())
  {
    Serial.print("http://www.google.com/maps/place/");
    Serial.print(gps.location.lat(), 6);
    Serial.print(F(","));
    Serial.println(gps.location.lng(), 6);
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  // Output date and time information
  Serial.print(F("Date/Time:"));
  if (gps.date.isValid())
  {
    Serial.print(gps.date.month());
    Serial.print(F("/"));
    Serial.print(gps.date.day());
    Serial.print(F("/"));
    Serial.print(gps.date.year());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F(" "));
  if (gps.time.isValid())
  {
    if (gps.time.hour() < 10) Serial.print(F("0"));
    Serial.print(gps.time.hour());
    Serial.print(F(":"));
    if (gps.time.minute() < 10) Serial.print(F("0"));
    Serial.print(gps.time.minute());
    Serial.print(F(":"));
    if (gps.time.second() < 10) Serial.print(F("0"));
    Serial.print(gps.time.second());
    Serial.print(F("."));
    if (gps.time.centisecond() < 10) Serial.print(F("0"));
    Serial.print(gps.time.centisecond());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.println();
}

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함