Hard fault when calling WiFi.off() - feature/hal

Hi all,

I wanted to upgrade my code to work with the new firmware (feature/hal branch) and noticed that now my code is broken. My core throws me a hard fault as soon as I call WiFi.off(). I made a small code example to show the issue. Anyone who can help me out?

Thank you!

/* Includes ------------------------------------------------------------------*/
#include "application.h"

SYSTEM_MODE(SEMI_AUTOMATIC);

/* This function is called once at start up ----------------------------------*/
void setup()
{
    WiFi.on();
    WiFi.clearCredentials();
    WiFi.setCredentials("ssid", "password");
    delay(3000);

    if (WiFi.hasCredentials()) {
        // Check for proper internet connection
        WiFi.connect();

        // Keep waiting for credentials untill given
        while (WiFi.connecting()) {}

        if (WiFi.ready())
            Spark.connect();
    }
}

/* This function loops forever --------------------------------------------*/
void loop()
{
    delay(5000);
    WiFi.off();
}

It shouldn’t create a hard fault, but I think SYSTEM_MODE(AUTOMATIC) and WiFi.off() won’t play well together anyway.

I tested all system modes to rule out that the cause was only present in SEMI_AUTOMATIC or MANUAL mode… I now changed my code example for the sake of clarity… :wink:
This code compiled online on spark builder does work on my core but when I try to use it with the feature/hal branch I get the hard fault…

Thanks for trying the feature/hal branch!

I’ve successfully reproduced the issue - I’ll get back to you later with a permanent fix.

The problem is related to the system closing the cloud socket after the call to WiFi.off() - ideally all sockets should be closed before shutting down the wifi module.

A temporary workaround would be to disconnect the cloud, and waiting for it to be disconnected before shutting off the wifi module.

2 Likes

Indeed closing the cloud and checking it is closed before calling WiFi.off() fixes the issue… I changed following file, spark_wiring_wifi.cpp by adding #include "delay_hal.h" on top and added following lines in the WiFiClass::off() method

void WiFiClass::off(void) {
    if (SPARK_WLAN_STARTED) {
        WiFiClass::disconnect(); // Added
        HAL_Delay_Microseconds(50000); //Added

        wlan_deactivate();
        ....

This works for me, does this look okay to you guys? I am new to changing the wrapper firmware, probably adding the delay is not a real good thing to do I guess?

1 Like