I have a problem using the PubSubClient. I want to create dynamic mqtt-topics based on a predefined prefix and a suffix and my ESP-macaddress.

My problem is that the PubSubClient requires a cost char* and I cant seem to figure out how to do it dynamically.

Below is my current solution and that is not as convenient as I want. The code below is only pseudocode but that are the crucial parts.

// How I get the mac_address
for (int i = 0; i < sizeof(mac_array); ++i){

// Current way, where I hard code the topic_in & topic_out
const char* topic_in = "node/18fe34d77ead/from_node_red";
const char* topic_out = "node/18fe34d77ead/to_node_red";

Below is an example of how I would love to do it but I cant figure out how to do it.

// I would love to be able to do like this
const char* topic_in = "node/"+mac_address+"/from_node_red";

Can any one please help me or point me in the right direction.


It doesn't require const char *, it says "passed string won't be changed inside of call". Externally it can be char * or char [] or Arduino String class with using c_str() method to get const char *.

And as the MAC address won't change a lot, it should be done once in the setup().


Try this:

String topicPreFix = "node/";
String mac = "18fe34d77ead";
String topicPostFix = "/from_node_red";
PubSubClient client ... ;

void setup(){

In your Method:

String myString = topicPreFix + mac + topicPostFix;
const char * msg = myString.c_str();
client.publish(msg ,"0");

Not the answer you're looking for? Browse other questions tagged or ask your own question.