wenbo2005.online

学习记录 / Arduino 与 ESP

获取 GPS

Arduino 与 ESP2024-10-22

改实例实现了将获取的经纬度,UTC时间,并将经纬度以 JSON 形式发送出去

(一),添加库:

#include <TinyGPS++.h>
#include <ArduinoJson.h>//json

(二),定义变量:

//gps
double lat,lng;
String Strlat,Strlng;
int hour, minute ,second;
int num_sat, speed;
TinyGPSPlus gps;

//JSON
StaticJsonDocument<200> doc_gps;

(三),数据处理(使用软串口接收GPS模块信息)

unsigned long read_gps_time=0;
void Read_GPS()
{
  if(millis() - read_gps_time < 200) return;
  read_gps_time = millis();

  boolean newData = false;
  while (AltGPS.available())//字符接收
  {
    if(gps.encode(AltGPS.read())>0)
    {
      newData = true;
      break;
    }
  }
  if(newData == true)
  {
    newData = false;
    Get_GPS();
  }
}

void Get_GPS()
{
  num_sat = gps.satellites.value();//获取卫星数量
  if (gps.location.isValid() == 1)
  {
    speed = gps.speed.kmph();
    lat = gps.location.lat();
    lng = gps.location.lng();//注意:直接使用Serial.println输出float类型只能保留两位小数!!
    //
    doc_gps["latitude"] = lat;
    doc_gps["longitude"] = lng;

    // 将JSON序列化为字符串
    char jsonBuffer[512];
    serializeJson(doc_gps, jsonBuffer);

    // 发送JSON数据
    Serial.println(jsonBuffer);
  }
  //UTC时间
  if (gps.time.isValid())
  {
    hour = gps.time.hour();
    minute = gps.time.minute();
    second = gps.time.second();
  }
}