Skip to content

Fix bug that sets pin 10 to INPUT on WiFi boards #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 22, 2020
Merged

Fix bug that sets pin 10 to INPUT on WiFi boards #22

merged 1 commit into from
Feb 22, 2020

Conversation

per1234
Copy link
Contributor

@per1234 per1234 commented Feb 18, 2020

netConnectionState being initialized to NetworkConnectionState::DISCONNECTED caused the WiFiNINA library's SpiDrv::end() to be called before SpiDrv::begin(). Since SLAVESELECT is initialized to 10, and only assigned SPIWIFI_SS in SpiDrv::begin(), this causes pin 10 to be set to INPUT. Since pin 10 is MISO on the MKR boards, and often used as CS on the Nano 33 IoT, and WiFiConnectionHandler::update() is typically called from loop(), after SPI has already been configured, this breaks communication on SPI.

Demonstration sketch:

#include <Arduino_ConnectionHandler.h>
#include <SD.h>
const char WiFiSSID[] = "ssid";
const char WiFiPassword[] = "pass";
const int SDchipSelect = 4;
WiFiConnectionHandler conMan(WiFiSSID, WiFiPassword);
void setup() {
  Serial.begin(9600);
  while (!Serial);
  Serial.print("Initializing SD card...");
  if (!SD.begin(SDchipSelect)) {
    Serial.println("Card failed, or not present");
    while (true);
  }
  Serial.println("card initialized.");
}
void loop() {
  conMan.update();
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.close();
    Serial.println("success opening file");
  }
  else {
    Serial.println("error opening file");
  }
}

Bug reported at:

netConnectionState being initialized to NetworkConnectionState::DISCONNECTED caused the WiFiNINA library's SpiDrv::end() to be called before SpiDrv::begin(). Since SLAVESELECT is initialized to 10, and only assigned SPIWIFI_SS in SpiDrv::begin(), this causes pin 10 to be set to INPUT. Since pin 10 is MISO on the MKR boards, and often used as CS on the Nano 33 IoT, and WiFiConnectionHandler::update() is typically called from loop(), after SPI has already been configured, this breaks communication on SPI.
@aentinger
Copy link
Contributor

I've successfully tested with a MKR WiFi 1010. From a logical point of view it makes sense to set the initial netConnectionState to NetworkConnectionState::INIT instead of NetworkConnectionState::DISCONNECTED. The state machine automatically transitions to from DISCONNECTED to INIT if keepAlive is true, ergo when keepAlive is false the connection manager in its current form would not even try to connect. Great work @per1234 👏

@ubidefeo I don't have anything with SD-Card at hand, can you please test this fix if it resolves your issue?

Copy link
Contributor

@aentinger aentinger left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test with MKR WiFi 1010 and works ... waiting for @ubidefeo testing with a SD card.

@ubidefeo
Copy link
Collaborator

I do, @aentinger
funny enough I packed that setup in my bag hoping I'f have time to take another look.
will test asap

@aentinger
Copy link
Contributor

@ubidefeo Any chance testing this change on your setup?

@ubidefeo
Copy link
Collaborator

testing it today, @aentinger
this week I've been in full-immersion with our workshop

@ubidefeo
Copy link
Collaborator

Works great
thank you very much, @per1234 🙏

@ubidefeo ubidefeo merged commit a498cd0 into arduino-libraries:master Feb 22, 2020
Copy link
Collaborator

@ubidefeo ubidefeo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Merged

@ubidefeo
Copy link
Collaborator

@per1234 @aentinger
I realised I tested while not calling ArduinoCloud.update(), and although this amend serves other purposes, I'm still unable to write to SD card using MKR WIFI 1010 and our own SD Proto Shield.

#include <SD.h>
#include <WiFiNINA.h>
#include <RTCZero.h>
#include "thingProperties.h"
#define CHIP_SEL 4
File logFile;

unsigned long lastTickTime;
#define TICK_INTERVAL 1000
RTCZero realTimeClock;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(19200);
  delay(3000);
  
  // Connect to Arduino IoT Cloud
  initProperties();
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  setDebugMessageLevel(4);
  ArduinoCloud.printDebugInfo();

  
  if(SD.begin(CHIP_SEL)){
    Serial.println("SD OK");
  }else{
    Serial.println("Failed to init SD Card");
  }
    
  lastTickTime = millis();
}

void loop()
{
  // put your main code here, to run repeatedly:
  unsigned long msNow = millis();
  ArduinoCloud.update();
  if (msNow - lastTickTime >= TICK_INTERVAL)
  {
    lastTickTime = msNow;
    updateCloudData();
    writeLogFile();
    listFiles();
  }
}

void updateCloudData()
{
  char fileName[13];
  secondCounter++;
  if (secondCounter >= 3600)
  {
    secondCounter = 0;
    hourCounter++;
  }
  uint32_t rtcEpoch = realTimeClock.getEpoch();
  Serial.println(realTimeClock.getYear());
  Serial.println(realTimeClock.getMonth());
  Serial.println(realTimeClock.getDay());
  Serial.print("EPOCH: ");
  Serial.println(rtcEpoch);
  Serial.println(fileName);
}

void writeLogFile()
{
  static int counterItem = 0;
  counterItem++;
  char bfr[12];
  sprintf(bfr, "file%d.log", counterItem);
  logFile = SD.open("file.log", FILE_WRITE);
  if(logFile){
    Serial.println("File created");
    logFile.close();
  }else{
    Serial.println("Could not create file");
  }
  
}

void onSecondCounterChange()
{
  Serial.print("seconds updated: ");
  Serial.println(secondCounter);
}
void onHourCounterChange()
{
  Serial.print("hour updated: ");
  Serial.println(hourCounter);
}

void updateLogFile()
{
  char fileName[13];
  sprintf(fileName, "20%d%02d%02d.log", realTimeClock.getYear(), realTimeClock.getMonth(), realTimeClock.getDay());
  Serial.println(fileName);
  File logFile = SD.open("datafile.log");
  logFile.print("hello");
  logFile.close();
  return;
  if (!logFile)
  {
    Serial.print("FAILED to open log file ");
    Serial.println(fileName);
    Serial.println("attempt at creating it");
    logFile = SD.open("datafile.log");
    if (!logFile)
    {
      Serial.println("UTTER FAILURE TO CREATE FILE datafile.log");
    }
  }
  if (logFile)
  {
    char dataSet[96];
    uint32_t timeStamp = realTimeClock.getEpoch();
    uint32_t freeMem = 0; //freeMemory();
    sprintf(dataSet, "%lu,%lu", timeStamp, freeMem);
    logFile.println(dataSet);
    logFile.close();
  }
}

void listFiles()
{
  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
    File root = SD.open("/");
    printDirectory(root, 2);
}

void printDirectory(File dir, int numTabs) {
  Serial.println("*** Directory ***");
  while (true) {

    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
  Serial.println("*** Directory ***");
}

@per1234
Copy link
Contributor Author

per1234 commented Feb 22, 2020

Using the same hardware as you and Arduino_ConnectionHandler @ f2a1b11 (the commit before this PR was merged) the output of the sketch is:

Could not create file

Files found on the card (name, date and size in bytes): 
*** Directory ***
*** Directory ***

Using Arduino_ConnectionHandler @ a498cd0 (the commit after this PR was merged) the output of the sketch is:

File created

Files found on the card (name, date and size in bytes): 
*** Directory ***
		SYSTEM~1/
*** Directory ***
			WPSETT~1.DAT		12
*** Directory ***
		FILE.LOG		0
*** Directory ***

Are you getting different results @ubidefeo?

@per1234 per1234 deleted the fix-spi branch February 22, 2020 19:55
@ubidefeo
Copy link
Collaborator

Found the culprit!

I was using arduino-cli and it kept using a cached compiled version of the library.
Then it hit me, triggered a clean, compiled/uploaded and it finally works.

Thank you for hunting this down.
I'm sure @Rocketct will also be happy this won't bother us in the future :)
🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants