Arduino - 无法连接到无线网络

Arduino - unable to connect to wifi

我有这段(部分)代码,用于从 SD 卡上的文本文件中读取 ssid 和密码。 然后应该使用此数据连接到本地 wifi。但是无法连接,并一直提示“正在建立与 WiFi 的连接...”

我似乎也无法打印从 SD 卡读取的内容。以前我的 readline 函数返回一个字符串。我能够正确打印并验证文件是否按预期读取。然后,由于 wifi 需要一个 Char*,我将代码更改为 Char*,此后它就不再工作了:

#include <SD.h>
#include <AccelStepper.h>
#include <MultiStepper.h>
#include <WiFi.h>
File myFile;
char* ssid;
char* password;


void setup() {
  // put your setup code here, to run once:

  pinMode(thetaPos, INPUT);
  pinMode(rhoPos, INPUT);

  Serial.begin(115200);
  Serial.print("Initializing SD card...");
  if (!SD.begin()) {
    Serial.println("initialization failed!");
    while (1);

  }
  Serial.println("initialization done.");
  myFile = SD.open("/config.txt");
  if (myFile) {
    // read from the file until there's nothing else in it:
    ssid = readLine();
    password = readLine();
    
      Serial.println(ssid);
      Serial.println(password);
  
  connectToNetwork();

    
    // close the file:
    myFile.close();
  } else {
    // file didn't open       
  }
 }
 
void loop() {
}


char* readLine() {
  char* received = "";
  char ch;
  while (myFile.available()) {
    ch = myFile.read();
    if (ch == '\n') {
      return received;
    } else {
      received += ch;
    }
  }
  return received;
}

void connectToNetwork() {
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Establishing connection to WiFi..");
  }
 
  Serial.println("Connected to network");
 
}

我做错了什么?

这是串行输出:

Initializing SD card...initialization done.
ore calibration nvs commit failed(0x%x)


wdt_config->intr_handle)
Establishing connection to WiFi..
Establishing connection to WiFi..
Establishing connection to WiFi..
Establishing connection to WiFi..

嗯,错误在哪里?这不会像您希望的那样工作:

char* readLine() {
  char* received = "";         // poiner to [=10=] somewhere... 
  char ch;
  while (myFile.available()) {
    ch = myFile.read();
    if (ch == '\n') {
      return received;
    } else {
      received += ch;          // move pointer to location ch bytes after...
    }
  }
  return received;
}

您正在使用指针算法 - 您正在内存中移动指针,并且没有在任何地方存储任何内容。重载 += char 并允许您将字符连接到它的末尾的不是字符串 class。

基本上你可以使用:

String readLine() {
  String received;
  while (myFile.available()) {
    ch = myFile.read();
    if (ch == '\n') {
      return received;
    } else {
      received += ch;
    }
  }
  return received;
}

它会起作用(尽管将一个字符一个字符地追加到字符串中不是一个好主意 - 通过这种方法堆内存会很快变得碎片化)

为避免其他错误,用法类似于:

String ssid = readLine();
String pass = readLine();

Wifi.begin(ssid.c_str(), pass.c_str());

//// definitely do not do something like:
// Wifi.begin(readLine().c_str(), readLine().c_str()); // !!! WRONG !!!
//// as the order of executing parameters isn't specified (and in the GCC it's from the last to the first)