Gabriel Godoi
Gabriel Godoi

Reputation: 1

ESP32 | How to assign a string to a char pointer?

I'm actually learning ESP32, its features and APIs.

My objective with this program is basically: to test some knowledges and techniques I've already developed and try, for the first time, an IoT application.

So, I have a class called myMQTT, it has two structs properties (NETWORK and MQTT):

class myMQTT{
  public:

  struct NETWORK
  {
    char *SSID, *PASSWORD, *IP;
  } NETWORK;

  struct MQTT
  {
    char *SEVER, *TOPIC, *USER, *PASSWORD;
    int PORT;
  } MQTT;

  myMQTT(){}

  void CONNECT(){

   }

};

How you can see, the structures give me pointers that I'd like to point to strings, like this:

void MQTTConnect(){

  myMQTT CONNECTION;

  CONNECTION.NETWORK.SSID = "SSID";  
  CONNECTION.NETWORK.PASSWORD = "1234";

  CONNECTION.MQTT.SEVER = "MQTT_SEVER";
  CONNECTION.MQTT.PORT = 1234;

  CONNECTION.MQTT.USER = "ESP32 | USER";
  CONNECTION.MQTT.PASSWORD = "ESP32 | PASS";
  CONNECTION.MQTT.TOPIC = "TEST";

  CONNECTION.CONNECT();

}

But the compiler gives me this warning:

ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

In examples on the internet, people usually code a MQTT connection using the libraries Wifi.h and PubSubClient.h, passing pointers as arguments to the classes methods:

#include <WiFi.h>
#include <PubSubClient.h>

// Replace the next variables with your SSID/Password combination
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Add your MQTT Broker IP address, example:
//const char* mqtt_server = "192.168.1.144";
const char* mqtt_server = "YOUR_MQTT_BROKER_IP_ADDRESS";

WiFiClient espClient;
PubSubClient client(espClient);

//CODE...

WiFi.begin(ssid, password);
client.setServer(mqtt_server, 1883);

//CODE...

Ref.: https://randomnerdtutorials.com/esp32-mqtt-publish-subscribe-arduino-ide/

I've already tried to use char arrays and Strings (Arduino Declaration).

I'd like to use the struct properties of my class to instance the other classes. How could I do that?

Upvotes: 0

Views: 3557

Answers (1)

Juraj
Juraj

Reputation: 3736

You do everything right, but because of a bug in Arduino builder in IDE 1.8.11 a wrong library is used. Instead of the ESP32 WiFi library, it uses the old Arduino WiFi library. In this library the parameters in WiFi.begin have type of char*. It was not a problem while the conversion from const char* to char* was reported only as a warning. But in esp boards packages it is an error.

The solution is to install the previous version of Arduino IDE 1.8.10 or 1.8.9.

Upvotes: 3

Related Questions