Issue with wifi on Xiao ESP32S3

Hello,

We bought two ESP32S3 at work as surveillance devices for long run experiments. Unfortunately, I could not achieve a reliable behavior of the wifi during the connection process. I used the standard example but WiFi.begin(ssid, password) works only after a manual reboot of the board using the button.

What steps I took to try to pinpoint the issue :

  • Using the same program at work and at home to see if it was related to one specific access point
  • Loading the program with VisualStudio/PlatformIO at work and Arduino-CLI at home
  • Rebooting the board by turning on and off the power of the RaspberryPi3’s internal usb hub I’m using at home using uhubctl
  • Soft rebooting the board by using the resetFunc function (ressource)
  • Hard rebooting the board by emulating the reset performed by the IDE after programming the board (ressource) ; my brother cleaned the Bash/C code of the original author for me, I’ll put the new one below and we will probably implement it in Python in the near future
  • Increasing pauses (from the original 100 ms to 10 s) between WiFi.disconnect(); and WiFi.begin(ssid, password);
  • Adding a step at which we wait for any user input by checking the size of the serial input buffer to manually start the wifi connection when our serial terminal is up to be sure to miss nothing

The thing I haven’t tried for now is to wire the EN pad to a digital output in order to simulate a push of the button directly in the program and avoid pushing on it manually. I still hope to understand the issue and have a more reliable behavior.

I also haven’t tried to adapt the standard test code to use different wifi functions (WiFi.disconnect(); with wifioff or eraseap parameters, WiFi.reconnect(), or WiFi.waitForConnectResult(), etc.).

Does someone have an idea on what I am doing wrong and/or what could be the solution?

EDIT: I played a little bit with WiFi.waitForConnectResult() and WiFi.status() and according to the Arduino reference, it seems that when calling WiFi.begin(), the status should switch to WL_IDLE_STATUS. But for me it is directly on WL_DISCONNECTED: at the function return value, right after the call, or until the end of the timeout. So it seems that WiFi.begin() is not behaving as it should for me.

Many thanks in advance!

Martin.


The last iteration of the wifi init code we tried:

void init_wifi() {
  // Set WiFi to STA mode and disconnect from an AP if it was previously connected
  Serial.print("Initializing WiFi");
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(1000);
  Serial.print(".");
  Serial.println();

  // Set WiFi to STA mode and connect to AP
  Serial.print("Connecting to WiFi");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  delay(1000);
  Serial.print(".");
  Serial.println();
  
  // Wait for opened connection
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println();

  // Print IP address
  Serial.print("Obtained IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println();
}

The code we used on the RaspberryPi to send a reset though the serial port (called with the serial port as an argument: ./ahr /dev/ttyACM0):

#include <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
  if (argc < 2) {
    fprintf(stderr, "need serial device\n");
    exit(1);
  }
  char* sport = argv[1];
  unsigned int delay = 1;

  int port_fd = open(sport, O_RDWR | O_NOCTTY);
  if (errno)
    printf("Error opening %s: %s (%d).\n", sport, strerror(errno), errno);
  int modem_ctrl, modem_ctrl_saved;
  if (ioctl(port_fd,TIOCMGET,&modem_ctrl_saved) == -1)
    printf("Error getting handshake lines: %s (%d).\n", strerror(errno), errno);
  modem_ctrl = (modem_ctrl_saved | TIOCM_RTS) & ~TIOCM_DTR;
  if (ioctl(port_fd, TIOCMSET, &modem_ctrl) == -1)
    printf("Error setting handshake lines: %s (%d).\n", strerror(errno), errno);
  sleep (delay);
  if (ioctl(port_fd, TIOCMSET, &modem_ctrl_saved) == -1)
    printf("Error setting handshake lines: %s (%d).\n", strerror(errno), errno);
  close(port_fd);
}

Hi there,
So does it get an IP address ? Is your DHCP working?
Do you have WPS turned on?
Lot’s to consider here. The reset button is required for initial boot of code after download to Xiao
after WiFi-Connect , disconnect and sleep can be used effectively.(sleep wakeup can be used to reset or resume.
HTH
GL :slight_smile: PJ

Curious to know if this code runs for you , The WPS example basically.
Press the WPS on your router. (either manually or from web page console)
Power on Xiao.

/*
THIS lightly tweeked PJG Example Code To Get ESP32c3 info from chip
 and to Connect WPS button AP and display RSSI, as well as do a BLE scan for devices.(WIP) concurrently 
 or as close as possible.
===========================================================
This example code provides both Push Button method and Pin
based WPS entry to get your ESP connected to your WiFi router.

Hardware Requirements
========================
ESP32 and a Router having WPS functionality

This code is under Public Domain License.

Author:
Pranav Cherukupalli <cherukupallip@gmail.com>
*/

#include "WiFi.h"
#include "esp_wps.h"
/*
Change the definition of the WPS mode
from WPS_TYPE_PBC to WPS_TYPE_PIN in
the case that you are using pin type
WPS
*/
//#include "SimpleBLE.h"
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
#include <U8x8lib.h>

#define ESP_WPS_MODE      WPS_TYPE_PBC
#define ESP_MANUFACTURER  "SEEED"
#define ESP_MODEL_NUMBER  "ESP32C3"
#define ESP_MODEL_NAME    "Xiao ESP"
#define ESP_DEVICE_NAME   "ESP STATION"


U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);

uint32_t chipId = 0;
long SCB;
static esp_wps_config_t config;
void(* resetFunc) (void) = 0; //declare reset function @ address 0
int scanTime = 5; //In seconds
BLEScan* pBLEScan;

class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
    void onResult(BLEAdvertisedDevice advertisedDevice) {
      //Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
    }
};

void setup(){
  Serial.begin(9600);
  delay(2000);
  u8x8.begin();
  u8x8.setFlipMode(1);   // set number from 1 to 3, the screen word will rotary 180*

  Serial.println();
   for(int i=0; i<17; i=i+8) {
	  chipId |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i;
	}

	Serial.printf("ESP32 Chip model = %s Rev %d\n", ESP.getChipModel(), ESP.getChipRevision());
	Serial.printf("This chip has %d cores\n", ESP.getChipCores());
  Serial.print("Chip ID: "); Serial.println(chipId);

  u8x8.setFont(u8x8_font_chroma48medium8_r);
  u8x8.setCursor(0, 0);
  u8x8.print("Looking for WPS");
	delay(2000);
  WiFi.onEvent(WiFiEvent);
  WiFi.mode(WIFI_MODE_STA);
  Serial.println("Starting WPS");
  wpsInitConfig();
  wpsStart();
  Serial.println("Scanning now...");
   while ( WiFi.status() != WL_CONNECTED) { //Wait for connection
   Serial.println(WiFi.localIP());
   delay(5000);
   // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("RSSI:");
  Serial.println(rssi);
  Serial.println("Scanning...BLE too!");
  u8x8.setCursor(0, 3);
  u8x8.print("Scanning...BLE too!");
  BLEDevice::init("");
  pBLEScan = BLEDevice::getScan(); //create new scan
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
  pBLEScan->setInterval(100);
  pBLEScan->setWindow(99);  // less or equal setInterval value
  //
  }
}
void loop(){
   //Serial.println(WiFi.localIP ());
 delay (2000);
 Serial.println("SoftwareReset");
  // put your main code here, to run repeatedly:
 // BLEScanResults foundDevices = pBLEScan->start(scanTime, false);
  //Serial.print("Devices found: ");
  //Serial.println(foundDevices.getCount());
  Serial.println("Scan done!");
  //pBLEScan->clearResults();   // delete results fromBLEScan buffer to release memory
  delay(10000);
 }


void wpsInitConfig(){
  config.wps_type = ESP_WPS_MODE;
  strcpy(config.factory_info.manufacturer, ESP_MANUFACTURER);
  strcpy(config.factory_info.model_number, ESP_MODEL_NUMBER);
  strcpy(config.factory_info.model_name, ESP_MODEL_NAME);
  strcpy(config.factory_info.device_name, ESP_DEVICE_NAME);
}

void wpsStart(){
    if(esp_wifi_wps_enable(&config)){
    	Serial.println("WPS Enable Failed");
    } else if(esp_wifi_wps_start(0)){
    	Serial.println("WPS Start Failed");
    }
}

void wpsStop(){
    if(esp_wifi_wps_disable()){
    	Serial.println("WPS Disable Failed");
    }
}
void resetfunc(){
  Serial.println("Soft reseting NOW");
  //NVIC_SystemReset();
}

String wpspin2string(uint8_t a[]){
  char wps_pin[9];
  for(int i=0;i<8;i++){
    wps_pin[i] = a[i];
  }
  wps_pin[8] = '\0';
  return (String)wps_pin;
}

void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info){
  switch(event){
    case ARDUINO_EVENT_WIFI_STA_START:
      Serial.println("Station Mode");
      break;
    case ARDUINO_EVENT_WIFI_STA_GOT_IP:
      Serial.println("Connected to :" + String(WiFi.SSID()));
      Serial.print("Got IP: ");
      Serial.println(WiFi.localIP());
      delay (2000);
      //NVIC_SystemReset();      // processor software reset
      break;
    case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
      Serial.println("Disconnected , attempt reconnect ");
      WiFi.reconnect();
      break;
    case ARDUINO_EVENT_WPS_ER_SUCCESS:
      Serial.println("WPS Successfull, connecting to: " + String(WiFi.SSID()));
      wpsStop();
      delay(10);
      WiFi.begin();
      break;
    case ARDUINO_EVENT_WPS_ER_FAILED:
      Serial.println("WPS Failed, retrying");
      wpsStop();
      wpsStart();
      break;
    case ARDUINO_EVENT_WPS_ER_TIMEOUT:
      Serial.println("WPS Timedout, retrying");
      wpsStop();
      wpsStart();
      break;
    case ARDUINO_EVENT_WPS_ER_PIN:
      Serial.println("WPS_PIN = " + wpspin2string(info.wps_er_pin.pin_code));
      break;
    default:
      break;
  }
}

HTH :+1:

i do know i had a XIAO ESP32S3 that refused to connect to wifi… it would just go …
it was eventually determined it must have a defect… it also connected once or twice just long enough to drive crazy

Dear PJ,


Thank you for your response.

Both DCHP (home & work) are working fine. For WPS, I will try when back home (it’s 5:30 pm around here). Obviously I don’t have access to a WPS button at work.

For the IP, when I reboot the Xiao through the physical button, it get one from the Acess Point. But as I never connect otherwise, I don’t get an IP.

Since my last edit, I finally understood how to activate verbose logs. Here are the last version of my wifi code and the logs associated:

Type any key to continue: 
Initializing WiFi...
Putting module in STA mode ([  6210][D][WiFiGeneric.cpp:1039] _eventCallback(): Arduino Event: 0 - WIFI_READY
1)
Disconnecting from previous AP ([  6245][V][WiFiGeneric.cpp:340] _arduino_event_cb(): STA Started
[  6246][D][WiFiGeneric.cpp:1039] _eventCallback(): Arduino Event: 2 - STA_START
[  6267][V][WiFiGeneric.cpp:343] _arduino_event_cb(): STA Stopped
[  6268][D][WiFiGeneric.cpp:1039] _eventCallback(): Arduino Event: 3 - STA_STOP
1)
Connecting to WiFi... 
Putting module in STA mode ([  7280][D][WiFiGeneric.cpp:1039] _eventCallback(): Arduino Event: 0 - WIFI_READY
1)
Begining connection ([  7282][V][WiFiGeneric.cpp:340] _arduino_event_cb(): STA Started
[  7284][D][WiFiGeneric.cpp:1039] _eventCallback(): Arduino Event: 2 - STA_START
[  7344][V][WiFiGeneric.cpp:97] set_esp_interface_ip(): Configuring Station static IP: 0.0.0.0, MASK: 0.0.0.0, GW: 0.0.0.0
6)
Initial status: WL_DISCONNECTED
Waiting for connection: [  9153][V][WiFiGeneric.cpp:362] _arduino_event_cb(): STA Disconnected: SSID: SFR-5690, BSSID: 24:7f:20:9e:56:96, Reason: 2
[  9154][D][WiFiGeneric.cpp:1039] _eventCallback(): Arduino Event: 5 - STA_DISCONNECTED
[  9155][W][WiFiGeneric.cpp:1061] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[  9155][D][WiFiGeneric.cpp:1081] _eventCallback(): WiFi Reconnect Running
[  9166][V][WiFiGeneric.cpp:97] set_esp_interface_ip(): Configuring Station static IP: 0.0.0.0, MASK: 0.0.0.0, GW: 0.0.0.0
[ 10263][V][WiFiGeneric.cpp:362] _arduino_event_cb(): STA Disconnected: SSID: SFR-5690, BSSID: 24:7f:20:9e:56:96, Reason: 2
[ 10264][D][WiFiGeneric.cpp:1039] _eventCallback(): Arduino Event: 5 - STA_DISCONNECTED
[ 10264][W][WiFiGeneric.cpp:1061] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[ 10265][D][WiFiGeneric.cpp:1085] _eventCallback(): WiFi AutoReconnect Running
[ 10267][V][WiFiGeneric.cpp:97] set_esp_interface_ip(): Configuring Station static IP: 0.0.0.0, MASK: 0.0.0.0, GW: 0.0.0.0
[ 11287][V][WiFiGeneric.cpp:362] _arduino_event_cb(): STA Disconnected: SSID: SFR-5690, BSSID: 24:7f:20:9e:56:96, Reason: 2
[ 11288][D][WiFiGeneric.cpp:1039] _eventCallback(): Arduino Event: 5 - STA_DISCONNECTED
[ 11288][W][WiFiGeneric.cpp:1061] _eventCallback(): Reason: 2 - AUTH_EXPIRE
[ 11289][D][WiFiGeneric.cpp:1085] _eventCallback(): WiFi AutoReconnect Running
void init_wifi() {
  // Set WiFi to STA mode and disconnect from an AP if it was previously connected
  Serial.println("Initializing WiFi...");

  Serial.print("Putting module in STA mode (");
  Serial.print(WiFi.mode(WIFI_STA));
  Serial.println(")");

  Serial.print("Disconnecting from previous AP (");
  Serial.print(WiFi.disconnect(true, true));
  Serial.println(")");

  delay(1000);

  // Set WiFi to STA mode and connect to AP
  Serial.println("Connecting to WiFi... ");

  Serial.print("Putting module in STA mode (");
  Serial.print(WiFi.mode(WIFI_STA));
  Serial.println(")");

  Serial.print("Begining connection (");
  Serial.print(WiFi.begin(ssid, password));
  Serial.println(")");

  Serial.print("Initial status: ");
  print_wifi_status_label();
  Serial.println();

  delay(1000);

  Serial.print("Waiting for connection: ");
  WiFi.waitForConnectResult(WIFI_CONNECTION_TIMEOUT);
  print_wifi_status_label();
  Serial.println();
  
  // Retries if necessary
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("Retrying... ");

    Serial.print("Calling reconnect (");
    Serial.print(WiFi.reconnect());
    Serial.println(")");

    Serial.print("Waiting for connection: ");
    WiFi.waitForConnectResult(WIFI_CONNECTION_TIMEOUT);
    print_wifi_status_label();
    Serial.println();

    if (WiFi.status() == WL_CONNECT_FAILED) {
      delay(WIFI_CONNECTION_TIMEOUT);
    }
  }

  // Print IP address
  Serial.print("Obtained IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println();
}

I seems to want to register an empty static IP. Next debug step on my side: try to force a static ip outside the DHCP range to see if it corrects the issue.

Hi there,
Here is some code I used a while back to help figure what I was doing.
It’s from Liam over at Arduino Forum.
It is a demo-code that has three useful additional functions,

// Demo-Code connect an ESP32 to a WiFi-network using stationmode STA

// stationmode is simply join the WiFi-network as your computer or smartphone does it
// the code has three useful functions one for easy identifiying the code in the flash
// one for non-blocking timing
// a heartbeat-blinker function for indicating the state the code is in

// the code is written with two programming rules:
// 1. put EACH functionality into its OWN function
// 2. give EACH function a SELF-explaining name what the function does
// you should follow these programming rules 
#include <WiFi.h>

const char *ssid     = "Your SSID";
const char *password = "your password";


void PrintFileNameDateTime() {
  Serial.println( F("Code running comes from file ") );
  Serial.println( F(__FILE__));
  Serial.print( F("  compiled ") );
  Serial.print(F(__DATE__));
  Serial.print( F(" ") );
  Serial.println(F(__TIME__));  
}


boolean TimePeriodIsOver (unsigned long &periodStartTime, unsigned long TimePeriod) {
  unsigned long currentMillis  = millis();  
  if ( currentMillis - periodStartTime >= TimePeriod )
  {
    periodStartTime = currentMillis; // set new expireTime
    return true;                // more time than TimePeriod) has elapsed since last time if-condition was true
  } 
  else return false;            // not expired
}

unsigned long MyTestTimer = 0;                   // variables MUST be of type unsigned long
const byte    OnBoard_LED = 2;


void BlinkHeartBeatLED(int IO_Pin, int BlinkPeriod) {
  static unsigned long MyBlinkTimer;
  pinMode(IO_Pin, OUTPUT);
  
  if ( TimePeriodIsOver(MyBlinkTimer,BlinkPeriod) ) {
    digitalWrite(IO_Pin,!digitalRead(IO_Pin) ); 
  }
}


void ConnectToWiFi() {
  WiFi.mode(WIFI_STA);
  Serial.println("WiFi.mode(WIFI_STA)");

  int myCount = 0;

  Serial.print("trying to connect to #");
  Serial.print(ssid);
  Serial.println("#");
  WiFi.begin(ssid, password);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED && myCount < 31) {
    BlinkHeartBeatLED(OnBoard_LED, 50); // blink LED fast during attempt to connect

    if ( TimePeriodIsOver(MyTestTimer, 500) ) { // once every 500 miliseconds
      Serial.print(".");                        // print a dot
       myCount++; 
       
      if (myCount > 30) { // after 30 dots = 15 seconds restart
        Serial.println();
        Serial.print("not yet connected executing ESP.restart();");
        ESP.restart();
      }
    }
  }

  if (WiFi.status() == WL_CONNECTED ) {
    Serial.println("");
    Serial.print("Connected to #");
    Serial.print(ssid);
    Serial.print("# IP address: ");
    Serial.println(WiFi.localIP());
  }

}

void setup() {
  Serial.begin(115200);
  Serial.println( F("Setup-Start") );
  PrintFileNameDateTime();
  ConnectToWiFi();
}

void PrintHelloMsg() {
  Serial.print( F("Hi there I'm the demo-code my IP address is: ") );
  Serial.println(WiFi.localIP());      
}


void loop() {
  BlinkHeartBeatLED(OnBoard_LED,500); // change blinking to a lower frequency indicating beeing connected

  if ( TimePeriodIsOver(MyTestTimer,1000) ) {
    PrintHelloMsg();
  }  
}



/*
most ESP32 boards have a blue LED connected to GPIO-pin 2
This blue LED is used to indicate state connecting to WiFi by blinking fast
state beeing connected to Wifi by blinking with 1 Hz

If the WiFi-connection is successfully established the serial monitor shows

08:44:02.915 -> Setup-Start
08:44:02.915 -> Code running comes from file 
08:44:02.915 -> your-path\ESP32-connect-to-Wifi-Demo-001\ESP32-connect-to-Wifi-Demo-001.ino
08:44:02.915 ->   compiled date/time of compiling
08:44:02.971 -> WiFi.mode(WIFI_STA)
08:44:02.971 -> trying to connect to #Your SSID#
08:44:03.362 -> ....
08:44:04.215 -> Connected to #Your SSID# IP address: given IP-adress NNN.NNN.NNN.NNN
08:44:04.865 -> Hi there I'm the demo-code my IP address is: NNN.NNN.NNN.NNN



if there is something wrong with your WiFi, SSID or password
you will see this in the serial monitor
08:32:36.598 -> Setup-Start
08:32:36.598 -> Code running comes from file 
08:32:36.598 -> F:\MyPortable-PRgs\arduino-1.8.16-newb\portable\sketchbook\ESP32-connect-to-Wifi-Demo-001\ESP32-connect-to-Wifi-Demo-001.ino
08:32:36.598 ->   compiled Dec  1 2021 08:32:18
08:32:36.684 -> WiFi.mode(WIFI_STA)
08:32:36.684 -> trying to connect to #your SSID#
08:32:37.036 -> ...............................
08:32:52.035 -> not yet connected executing ESP.restart();ets Jun  8 2016 00:22:57
08:32:52.035 -> 
08:32:52.035 -> rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
08:32:52.035 -> configsip: 0, SPIWP:0xee
08:32:52.035 -> clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
08:32:52.073 -> mode:DIO, clock div:1
08:32:52.073 -> load:0x3fff0018,len:4
08:32:52.073 -> load:0x3fff001c,len:1216
08:32:52.073 -> ho 0 tail 12 room 4
08:32:52.073 -> load:0x40078000,len:9720
08:32:52.073 -> ho 0 tail 12 room 4
08:32:52.073 -> load:0x40080400,len:6352
08:32:52.073 -> entry 0x400806b8
08:32:52.309 -> Setup-Start
08:32:52.309 -> Code running comes from file 
08:32:52.309 -> F:\MyPortable-PRgs\arduino-1.8.16-newb\portable\sketchbook\ESP32-connect-to-Wifi-Demo-001\ESP32-connect-to-Wifi-Demo-001.ino
08:32:52.309 ->   compiled Dec  1 2021 08:32:18
08:32:52.405 -> WiFi.mode(WIFI_STA)
08:32:52.405 -> trying to connect to #Your SSID#
08:32:52.758 -> ...............................
08:33:07.788 -> not yet connected executing ESP.restart();ets Jun  8 2016 00:22:57

 */

Be sure antenna is attached properly , what kind of RSSI 's are you seeing. Near and Far?
HTH
GL :slight_smile: PJ

Try this code if you have expansion board with SD installed

#include "FS.h"
#include "SD.h"
#include "SPI.h"
#include <time.h> 
#include <WiFi.h>

//#define SD_chipSelect D2 //XIAO 
#define SD_chipSelect 21 //XIAO ESP32S3 Cam Board

const char* ssid     = "your-ssid";
const char* password = "your-password";

long timezone = -5; 
byte daysavetime = 0;

void listDir(fs::FS &fs, const char * dirname, uint8_t levels)
{//Begin
  Serial.printf("Listing directory: %s\n", dirname);

  File root = fs.open(dirname);
  if(!root)
  {//Begin
    Serial.println("Failed to open directory");
    return;
  }//  End
  if(!root.isDirectory())
  {//Begin
    Serial.println("Not a directory");
    return;
  }//  End
  File file = root.openNextFile();
  while(file)
  {//Begin
    if(file.isDirectory())
    {//Begin
      Serial.print("  DIR : ");
      Serial.print (file.name());
      time_t t= file.getLastWrite();
      struct tm * tmstruct = localtime(&t);
      Serial.printf("  LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec);
      if(levels)
      {listDir(fs, file.path(), levels -1);}
    }//  End 
    else 
    {//Begin
      Serial.print("  FILE: ");
      Serial.print(file.name());
      Serial.print("  SIZE: ");
      Serial.print(file.size());
      time_t t= file.getLastWrite();
      struct tm * tmstruct = localtime(&t);
      Serial.printf("  LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec);
    }//  End
  file = root.openNextFile();
  }//  End
}//  End

void createDir(fs::FS &fs, const char * path)
{//Begin
  Serial.printf("Creating Dir: %s\n", path);
  if(fs.mkdir(path))
    {Serial.println("Dir created");} 
  else 
    {Serial.println("mkdir failed");}
}//  End

void removeDir(fs::FS &fs, const char * path)
{//Begin
  Serial.printf("Removing Dir: %s\n", path);
  if(fs.rmdir(path))
    {Serial.println("Dir removed");} 
  else 
    {Serial.println("rmdir failed");}
}//  End

void readFile(fs::FS &fs, const char * path)
{//Begin
  Serial.printf("Reading file: %s\n", path);
  File file = fs.open(path);
  if(!file)
  {//Begin
    Serial.println("Failed to open file for reading");
    return;
  }//  End
  Serial.print("Read from file: ");
  while(file.available())
  {Serial.write(file.read());}
  file.close();
}//  End

void writeFile(fs::FS &fs, const char * path, const char * message)
{//Begin
  Serial.printf("Writing file: %s\n", path);
  File file = fs.open(path, FILE_WRITE);
  if(!file)
  {//Begin
    Serial.println("Failed to open file for writing");
    return;
  }//  End
  if(file.print(message))
    {Serial.println("File written");}
  else 
    {Serial.println("Write failed");}
  file.close();
}//  End

void appendFile(fs::FS &fs, const char * path, const char * message)
{//Begin
  Serial.printf("Appending to file: %s\n", path);
  File file = fs.open(path, FILE_APPEND);
  if(!file)
  {//Begin
    Serial.println("Failed to open file for appending");
    return;
  }//  End
    if(file.print(message))
    {Serial.println("Message appended");}
  else 
    {Serial.println("Append failed");}
  file.close();
}//  End

void renameFile(fs::FS &fs, const char * path1, const char * path2)
{//Begin
  Serial.printf("Renaming file %s to %s\n", path1, path2);
  if (fs.rename(path1, path2)) 
    {Serial.println("File renamed");}
  else 
    {Serial.println("Rename failed");}
}//  End

void deleteFile(fs::FS &fs, const char * path)
{//Begin
  Serial.printf("Deleting file: %s\n", path);
  if(fs.remove(path))
    {Serial.println("File deleted");} 
  else 
    {Serial.println("Delete failed");}
}//  End

void setup()
{//Begin
  Serial.begin(19200);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) 
  {//Begin
    delay(500);
    Serial.print(".");
  }//  End
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Contacting Time Server");
	configTime(3600*timezone, daysavetime*3600, "time.nist.gov", "0.pool.ntp.org", "1.pool.ntp.org");
	struct tm tmstruct ;
  delay(2000);
  tmstruct.tm_year = 0;
  getLocalTime(&tmstruct, 5000);
	Serial.printf("\nNow is : %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct.tm_year)+1900,( tmstruct.tm_mon)+1, tmstruct.tm_mday,tmstruct.tm_hour , tmstruct.tm_min, tmstruct.tm_sec);
  Serial.println(""); 
  if(!SD.begin(SD_chipSelect))
  {//Begin
    Serial.println("Card Mount Failed");
    return;
  }//  End
  uint8_t cardType = SD.cardType();
  if(cardType == CARD_NONE)
  {//Begin
    Serial.println("No SD card attached");
    return;
  }//  End
  Serial.print("SD Card Type: ");
  if(cardType == CARD_MMC)
    {Serial.println("MMC");}
  else if(cardType == CARD_SD)
    {Serial.println("SDSC");} 
  else if(cardType == CARD_SDHC)
    {Serial.println("SDHC");} 
  else 
    {Serial.println("UNKNOWN");}
  uint64_t cardSize = SD.cardSize() / (1024 * 1024);
  Serial.printf("SD Card Size: %lluMB\n", cardSize);
  listDir(SD, "/", 0);
  removeDir(SD, "/mydir");
  createDir(SD, "/mydir");
  deleteFile(SD, "/hello.txt");
  writeFile(SD, "/hello.txt", "Hello ");
  appendFile(SD, "/hello.txt", "World!\n");
	listDir(SD, "/", 0);
  Serial.printf("All Done!....");
}//  End

void loop()
{}

Hi there,
You may want to “flush” serial port b4 the next connection, I have seen that jam up multiple wifi, ap connects…
HTH
GL :slight_smile: PJ

Hello all,


Thank you for all your responses. I progressed on the matter yesterday night at home. The board at home actually connects to the wifi but it takes an insane amount of time! I made multiple runs and it connects each time, after a delay between 4 and 12 minutes! So it appears using the hardware button was just shortening this waiting time to a reasonable amount.

The issue seems to be different at work, as I can not replicate the same behavior. While using the corporate wifi or my phone as Access Point. So my quest is not over :sweat_smile:.

In order to respond to all your suggestions:

  • @PJ_Glasso: Because I discovered that effect and was focuse don it, I didn’t try the WPS button yet
  • @PJ_Glasso: Yes, the antenne is attached properly. The board at home is about five meters from the Access Point with only a wood pannel between them (RSSI -63) and the board at work is maybe ten meters away in direct line of sight (RSSI -52 using my phone).
  • @cgwaltney: No SD attached but there is stuff in your code I wanted to use for debugging my issues (using a NTP server for logging in long runs for example). Thanks for it!
  • @PJ_Glasso: Flushing serial doesn’t seem to improve the issue for now


Martin.

1 Like