Esp32 Connecting to Wi-Fi Using String Ssid
I Cannot Connect to Wi-Fi on My Esp32 Dev-Kit; I Have a String Which Contains Ssid and Password, but the Wifi. Begin() Function Accepts Only Const Char*, and I...
I cannot connect to Wi-fi on my ESP32 DEV-KIT; I have a String which contains ssid and password, but the WIFI.begin() function accepts only const char*, and I don't know how to convert String to const char*. I have tried the c_str() function, but the result I am getting is != (not equal) to the actual ssid.
String ssid = "DIR-615A";
char ssidR;
const char* ssidR2 = "DIR-615A";
void setup() {
ssidR = ssid.c_str();
Serial.println(ssidR);
Serial.println(ssidR2);
Serial.println(ssidR == ssidR2); //this returns 0
}
Both ssidR and ssidR2 look identical when printing them, but when I use ssidR to connect to wi-fi, it is not working.
2 Answers
You can use toCharArray() to convert the String object into an array of chars.
Also, you have to use strcmp() to compare two strings, otherwise you're literally just comparing the address in memory where the data is kept.
To use it:
char ssid_char[100]; /* or however long your SSID is going to be */
ssid.toCharArray(ssid_char, ssid.length());
wifi.begin(ssid_char);
The reason is that you need space to store the content of the string somewhere. Your ssidR variable was just a pointer to memory, but there was no memory to store the actual string. By using a static array, the memory is reserved for the toCharArray() call to fill.
I was going to try to put this as a comment, but it's unwieldy there. It's kind of screwed up as an answer, because your question seems to be predicated on an misunderstandings of what to expect from == and const char * and what can be done with a single char, but it does at least address what's been said.
Must Read
Regarding /*char*/ ssidR = ssid.c_str(); and ssidR == ssidR2
I addressed this part in a comment, but since as though I'm making an answer now I'll pull it into here. I'm not repeating this just to beat a dead horse.
You are attempting to assign a pointer to const char to a single char. Basically you're trying to cram 32bit (in this case) address of something into a character and then you're trying to compare that with const char * again:
Serial.println(ssidR == ssidR2); //this returns 0
Right, it would do. Without splitting hairs about the language standard and undefined behaviour on overflow, etc. what you're doing here is comparing the low byte of the address of the buffer maintained by your String object with the full address of your string literal "DIR-615A" and they're not equal.