簡體   English   中英

Arduino MKRGSM 1400 在連接到 MQTT 時崩潰

[英]Arduino MKRGSM 1400 crashes when connecting to MQTT

我有一個關於 Arduino MKRGSM 1400 和 MQTT 的問題。

我使用下面的代碼通過 SIM 卡將我的 MKRGSM 連接到互聯網,然后將其連接到我在 Docker 上安裝的 HiveMQ 代理。 即使代碼編譯沒有任何錯誤,一旦我將它上傳到我的板上,它就會崩潰。 一旦它崩潰了,我必須完全重置我的電路板。 我已經在 VS Code 上使用 Arduino IDE 和 Platform.io 嘗試了這段代碼,兩者都給出了相同的結果。

在我進行 MQTT 連接之前,電路板已成功連接到互聯網,並且 DHT11 傳感器能夠毫無問題地讀取濕度和溫度值。

我不擅長 Arduino,這是我第一次嘗試自己使用 MQTT。

有誰知道為什么代碼不僅不起作用,而且還會使我的電路板崩潰? 提前致謝!

//Includes
#include <PubSubClient.h>
#include <MKRGSM.h>
#include "DHT.h"
#include <Adafruit_Sensor.h>

//Var declaration
//SIM-internet connection
GSMClient net;
GPRS gprs;
GSM gsmAccess;

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

//MQTT connection
PubSubClient client;
const String serialNumber = "1";
const String mqtt_server = "server_ip";
const String topic = "/prototype/" + serialNumber;

//DHT sensor PIN declaration
#define DHTPIN 2  //DHT is pinned on 2
#define DHTTYPE DHT11 
DHT dht(DHTPIN, DHTTYPE);

void connect() {
//SIM not connected
    bool connected = false;
    Serial.print("Connecting to cellular network.");

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

void setup() {
    Serial.begin(9600);

    //Connect to Docker MQTT
    client.setServer(mqtt_server.c_str(), 8086);
    client.connect(serialNumber.c_str());
    Serial.print("MQTT connection state: ");
    Serial.println(client.state());

    //Start DHT 11
    dht.begin();
}

void loop() {
    delay(10000);

    //Get DHT values
    float humidty = dht.readHumidity();
    float temperature = dht.readTemperature();

    //Create JSON out of values and send it.
    const String json = "{\"temperature\": " + String(temperature, 2) + ", \"humidity\": " + String(humidty) + " }";
    Serial.println(json);
    client.publish(topic.c_str(), json.c_str());

    //Check if MQTT connection is holding.
    Serial.print("MQTT connection state: ");
    Serial.println(client.state());

    //Reconnect if MQTT connection is lost.
    if (!client.connected()) {
    Serial.println("MQTT disconnected! Trying reconnect.");
    client.connect("whatever");
  }

}

正如評論中所說的那樣

您從未調用過connect()函數,因此從未設置過 GSM 網絡。

然后您可能需要使用 GSMClient 來初始化 PubSubClient,以便它知道如何訪問網絡。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM