# Arduino MKR NB does not connect to internet after first failure

**URL:** <https://forum.arduino.cc/t/arduino-mkr-nb-does-not-connect-to-internet-after-first-failure/910528>\
**Category:** Programming\
**Created:** [September 30, 2021, 8:19pm UTC](https://forum.arduino.cc/t/arduino-mkr-nb-does-not-connect-to-internet-after-first-failure/910528 "2021-09-30T20:19:30Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![dkanday](https://avatars.discourse-cdn.com/v4/letter/d/8edcca/32.png) [@dkanday](https://forum.arduino.cc/u/dkanday)\
**Post date:** [September 30, 2021, 8:19pm UTC](https://forum.arduino.cc/t/arduino-mkr-nb-does-not-connect-to-internet-after-first-failure/910528/1 "2021-09-30T20:19:30Z")

</div>

Hi,

I am using Arduino MKR 1500 and the issue I am having is when the Arduino initiates, it tries to connect to internet. If it fails at the time of initiation, I reset it by hitting the button or I have a watchdog which resets the micro if it fails. The issue is after reset it never connects or sometime it hangs up and I have to click the reset button twice, load the bootloader firmwareand load the firmware again. Here is my code for reference.

```cpp
#include <ArduinoMqttClient.h>
#include <MKRNB.h>

// Please enter your sensitive data in the Secret tab or arduino_secrets.h
// PIN Number
const char PINNUMBER[] = "";

// MQTT Broker and Port
const char broker[] = "test.mosquitto.org"; //
int port = 1883;

// Pub/Sub Topics - Make it something unique since we are using a public broker
const char subscribeTopic[] = "channel";
const char publishTopic[] = "channel";

// To connect with SSL/TLS:
// 1) Change NBClient to NBSSLClient.
// 2) Change port value from 1883 to 8883.
// 3) Change broker value to a server with a known SSL/TLS root certificate 
// flashed in the WiFi module.

NBClient client;
GPRS gprs;
NB nbAccess;
MqttClient mqttClient(client);

int LED = 6; // Onboard LED

// Publish interval
long previousMillis = 0; 
long interval = 2000;

void setup() {

  pinMode(LED_BUILTIN, OUTPUT); // Set built in LED pinMode
  
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
 /* while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }*/

  // attempt to connect to GSM and GPRS:
  Serial.print("Attempting to connect to GSM and GPRS");
   // connection state
  bool connected = false;

  // After starting the modem with GSM.begin()
  // attach the shield to the GPRS network with the APN, login and password
  while (!connected) {
    if ((nbAccess.begin(PINNUMBER) == NB_READY) &&
        (gprs.attachGPRS() == GPRS_READY)) {
      connected = true;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("You're connected to the network");
  Serial.println();

  Serial.print("Attempting to connect to the MQTT broker: ");
  Serial.println(broker);

  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());

    while (1);
  }

  Serial.println("You're connected to the MQTT broker!");
  Serial.println();

  // set the message receive callback
  mqttClient.onMessage(onMqttMessage);

  Serial.print("Subscribing to topic: ");
  Serial.println(subscribeTopic);
  Serial.println();

  // subscribe to a topic
  mqttClient.subscribe(subscribeTopic);

  Serial.print("Waiting for messages on topic: ");
  Serial.println(subscribeTopic);
  Serial.println();
}

void loop() {
  unsigned long currentMillis = millis(); 
  
  // call poll() regularly to allow the library to receive MQTT messages and
  // send MQTT keep alives which avoids being disconnected by the broker
  mqttClient.poll();

  // Enforce Interval
  if(currentMillis - previousMillis > interval) {
        previousMillis = currentMillis;

        // Call a function that handles publishing message
        publishSensorVal();
      
  }
}

void publishSensorVal() {
    // read the first Analog pin
    int sensorVal = analogRead(0);     
    //String speak = "The sensor val is " + String(sensorVal);
    char adc_sv[30] = {'T', 'h', 'e', ' ', 'a', 'd', 'c', ' '' ', 'v', 'a', 'l', 'u', 'e', ' ', 'i', 's', ' ', '\0'}; //adc_step value
    // Publish our sensor value to the publish topic
    mqttClient.beginMessage(publishTopic);
    mqttClient.print(adc_sv);
    mqttClient.print(sensorVal);
    mqttClient.endMessage();
      digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
  delay(1400); // wait for a second
  digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
  delay(100); // wait for a second
}

void handleCommand(String cmd) {
  if (cmd == "on"){
    digitalWrite(LED, HIGH);
  }else if(cmd == "off"){
    digitalWrite(LED, LOW);
  }
}

void onMqttMessage(int messageSize) {
  // we received a message, print out the topic and contents
  Serial.println("Received a message with topic '");
  Serial.print(mqttClient.messageTopic());
  Serial.print("', length ");
  Serial.print(messageSize);
  Serial.println(" bytes:");

  // We want to read each character into a useable String
  String content = "";
  char character;
  
  // use the Stream interface to print the contents
  while (mqttClient.available()) {
    character = (char)mqttClient.read();
    content.concat(character);
  }

  handleCommand(content); // This function does something with our incoming string

  Serial.println(content);
  Serial.println(); Serial.println(); // double spacing
}

```

Any help is much appreciated

---

<div class="post-metadata">

**Author:** ![pylon](https://avatars.discourse-cdn.com/v4/letter/p/59ef9b/32.png) [@pylon](https://forum.arduino.cc/u/pylon)\
**Post date:** [October 1, 2021, 5:12pm UTC](https://forum.arduino.cc/t/arduino-mkr-nb-does-not-connect-to-internet-after-first-failure/910528/2 "2021-10-01T17:12:36Z")

</div>

> [@dkanday](#):
>
> ```arduino
> if ((nbAccess.begin(PINNUMBER) == NB_READY) &&
> (gprs.attachGPRS() == GPRS_READY)) {
> connected = true;
> } else {
> 
> ```

Why do you insist on the GPRS connection?

What serial output do you get in these cases?

> [@dkanday](#):
>
> ```arduino
> if (!mqttClient.connect(broker, port)) {
> Serial.print("MQTT connection failed! Error code = ");
> Serial.println(mqttClient.connectError());
> 
> while (1);
> }
> 
> ```

You know that this kind of freezes your board if there is any connection problem, don't you?

---

<div class="post-metadata">

**Author:** ![dkanday](https://avatars.discourse-cdn.com/v4/letter/d/8edcca/32.png) [@dkanday](https://forum.arduino.cc/u/dkanday)\
**Post date:** [October 1, 2021, 6:02pm UTC](https://forum.arduino.cc/t/arduino-mkr-nb-does-not-connect-to-internet-after-first-failure/910528/3 "2021-10-01T18:02:47Z")

</div>

When there is a connection error with the MQTT broker it gives me a error message like error 1 is MQTT is unable to connect as it lost internet connection and 2 is invalid mqtt credentials.

My application streams data to the cloud and that is why I am waiting for internet connection.

---

<div class="post-metadata">

**Author:** ![pylon](https://avatars.discourse-cdn.com/v4/letter/p/59ef9b/32.png) [@pylon](https://forum.arduino.cc/u/pylon)\
**Post date:** [October 1, 2021, 6:52pm UTC](https://forum.arduino.cc/t/arduino-mkr-nb-does-not-connect-to-internet-after-first-failure/910528/4 "2021-10-01T18:52:47Z")

</div>

Again: post the serial output you get after a reset!

> [@dkanday](#):
>
> My application streams data to the cloud and that is why I am waiting for internet connection.

But you don't use the GPRS connection so you don't need it (given you mean the GPRS connection by "internet connection").

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [March 30, 2022, 6:53pm UTC](https://forum.arduino.cc/t/arduino-mkr-nb-does-not-connect-to-internet-after-first-failure/910528/5 "2022-03-30T18:53:02Z")

</div>

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.
