首页 > 解决方案 > 连接到 MQTT 时,Arduino MKRGSM 1400 给出的位置不正确

问题描述

我正在尝试从我的 mkrgsm 1400 中提取位置数据并将其发送到 mqtt。几天来,我一直在努力解决同时运行 GSM 和 MQTT 时产生的不准确坐标。我已经使用基本的 MKRGSM 示例代码“GsmLocation”测试了我的 arduino,发现它会拉出非常准确的坐标(我在一个建成的城市,所以有很多手机信号塔),但是一旦我尝试添加一个连接到MQTT GSM 将给出默认坐标 54、-2(根本不在我附近)或在城市另一边的坐标。我不明白为什么实施 MQTT 会抛出坐标。

编辑:我一直在做很多实验来排除任何可能导致这个问题的可能性。我已经尝试过使用 MQTT 库和 PubSubClient 库,它们都给出了相同的抛出坐标。我认为我的问题可能是当我尝试发布到 mqtt(这可以是任何消息 - 不是特定于位置)时,它似乎会抛出坐标,我不确定 mqtt 连接和位置连接是否是有点互相打架?也许有一种不同的方式来布置可以阻止这种情况的代码?

这是我的代码:

#include <MKRGSM.h>
#include <MQTT.h>
#include <avr/dtostrf.h>

const char pin[]      = "";
const char apn[]      = "";
const char login[]    = "";
const char password[] = "";

GSMLocation location;
GSMClient net;
GPRS gprs;
GSM gsmAccess;
MQTTClient client;
char pubCharsPayload[100];

void connect() {
  // connection state
  bool connected = false;

  Serial.print("connecting to cellular network ...");
  while (!connected) {
    if ((gsmAccess.begin(pin) == GSM_READY) &&
        (gprs.attachGPRS(apn, login, password) == GPRS_READY)) {
      connected = true;
      Serial.println("Connected to cellular network!");
    } else {
      Serial.print(".");
      delay(1000);
    }
  }

  Serial.print("Connecting to MQTT...");
  while (!client.connect("","","")) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("Connected to MQTT!");

  client.subscribe("/location");
}

void messageReceived(String &topic, String &payload) {
  Serial.println("incoming: " + topic + " - " + payload);
}

void setup() {
  Serial.begin(115200);
  client.begin("broker.shiftr.io", net);
  client.onMessage(messageReceived);

  connect();
  location.begin();
}

void loop() {
  client.loop();

  if (!client.connected()) {
    connect();
  }

if (location.available()){
    //Construct the string for the latitude
    char bufferLat[20];
    //Uses dtostrf library to convert
    String latVal = dtostrf(location.latitude(), 10, 7, bufferLat);
    //Construct the string for the longitude
    char bufferLon[20];
    String lonVal = dtostrf(location.longitude(), 10, 7, bufferLon);
      char bufferAcc[20];
    String accVal = dtostrf(location.accuracy(), 10, 7, bufferAcc);

    //Construct the payload as a JSON object
    String payload = "{\"Latitude\":" + latVal + ",\"Longitude\":" + lonVal + ",\"Accuracy\":" + accVal + "}";
//        String payload = "{\"Latitude\":" + latVal + ",\"Longitude\":" + lonVal + "}";
    payload.toCharArray(pubCharsPayload, (payload.length() + 1));
    //Pushes data to MQTT every 12000 milliseconds
    delay(5000);
    client.publish("/location", pubCharsPayload);
}
}
`


标签: arduinomqttgsmarduino-c++

解决方案


推荐阅读