如何传递一个变量给wifiManager.autoConnect()来命名AP



我试图让我的ESP8266将AP名称设置为Stand + MAC地址减去分号,如Stand5CCF7F238734

我写的GetMyMacAddress()函数显然是工作的,串行输出显示。

每次我尝试将字符串或字符变量传递给wifiManager.autoConnect()时,我会得到编译器错误。即使头文件标识字符串类型。

如果我通过macStr*macStr

从'char'转换为'const char*'无效[-fpermissive]

如果我传递ap2(字符串类型),我得到:

没有匹配的函数来调用'WiFiManager::autoConnect(String&)'

我代码:

#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
String ap = "Stand";
String ap2;
uint8_t mac[6];
char const macStr[19] = {0};
void setup() {
    Serial.begin(115200);
    WiFiManager wifiManager;  //WiFiManager -- Local intialization.
    ap2 = ap + GetMyMacAddress();
    //std::string ap2;
    char *macStr = new char[ap2.length()+ 1 ];
    strcpy(macStr, ap2.c_str());
    //fetches ssid and pass from eeprom and tries to connect
    //if connect fails it starts an access point with the specified name
    //here  "AutoConnectAP" and goes into a loop awaiting configuration
    wifiManager.autoConnect( "Stand" );
    //or use this for auto generated name ESP + ChipID
    //wifiManager.autoConnect();
    //if you get here you have connected to the WiFi
    Serial.println("connected...yeey :)");
    Serial.print("ap2"); Serial.print("    " ); Serial.print( ap2); Serial.println(" String");
    Serial.print("macStr"); Serial.print(" "); Serial.print( macStr ); Serial.println(" Char");
}
void loop() {
}
String GetMyMacAddress()
{
  uint8_t mac[6];
  char macStr[18] = {0};
  WiFi.macAddress(mac);
  sprintf(macStr, "%02X%02X%02X%02X%02X%02X", mac[0],  mac[1], mac[2], mac[3], mac[4], mac[5]); // no :'s
  // sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0],  mac[1], mac[2], mac[3], mac[4], mac[5]);  // with :'s
  return  String(macStr);
}

连接后,串行输出:

connected...yeey :)
ap2    Stand5CCF7F238734 String
macStr Stand5CCF7F238734 Char

如果你想使用ap2字符串对象,你需要使用它的char数组和const强制转换,如:

wifiManager.autoConnect((const char*)ap2.c_str());

我不明白为什么你使用动态分配的macStr, ap2的字符数组将足以处理它。尽管如此,如果你想使用它,可以这样尝试:

wifiManager.autoConnect((const char*)macStr);

祝你好运!

相关内容

最新更新