Arduino - 无法连接到 wifi

时间:2021-02-14 18:39:17

标签: string arduino char 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..

1 个答案:

答案 0 :(得分:1)

那么,错误在哪里?这不会如您所愿:

char* readLine() {
  char* received = "";         // poiner to \0 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 并允许您将字符连接到它的末尾的不是 String 类。

基本上你可以使用:

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

并且它会起作用(尽管将一个字符一个字符地附加到 String 并不是一个好主意 - 通过这种方法堆内存会很快被碎片化)

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

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)