arduino - 连接到 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);
}
}
`
解决方案
推荐阅读
- flutter - Flutter - 如何询问用户访问存储/消息的权限?
- python - 如何在 Python 中监听常规键和组合键
- javascript - 在明暗模式之间切换
- windows - Oracle(sqlplus 不被识别为内部或外部命令)
- javascript - 自定义 ::-webkit-scrollbar 会破坏以前的功能?
- php - 在 WooCommerce 中显示销售车商品格式的价格范围
- mysql - 即使没有找到值,也可以加入两个表分组并计数(显示为 0)
- postgresql - Postgres 约束,其中 col1 不能与 col2 相同
- lua - Lua - 创建用户驱动的菜单 - 终端界面 - 如何最好地导航?
- java - 此代码使用什么公式来计算 pf Pi 的值?