Settings Text String as Variable in If Statement

Hey Guys -

Quick newb question, please. I've got code for a project which publishes MQTT strings based on the results of a gesture sensor. Skipping all the setup stuff, the line that does the magic is..

snprintf (msg, 75, "up");
client.publish("server1", msg);

which publishes the payload "up" to the MQTT topic "server1" & works great.

My Issue
I'm planning to have a physical toggle switch on the side of the device and depending on its position, want to to either "server1" or "server2" therefore need to replace "server1" above with a variable like "server" which I can then flipflop to either one. Below is the last failed coding snippet pertaining only to the physical switch, desired variable, and part of code that publishes the topic that will use the variable.

const byte switchPin0 = D5;
char mediacenter = "server1";

void setup() {
  pinMode(switchPin0, INPUT_PULLUP);
}

void loop() {
byte switchState0 = digitalRead(switchPin0);
if (switchState0 == LOW) {
String(server) = "server1";
} else {
String(server) = "server2"; }
...
snprintf (msg, 75, "up");
client.publish(server, msg);  //Uses variable set above (hopefully)

Any suggestions? Thanks!

if you can use a c-string ptr, how about

const byte switchPin0 = D5;

char mediacenter = "server1";
char *pServer;

void setup() {
    pinMode(switchPin0, INPUT_PULLUP);
}

void loop() {
    if (digitalRead(switchPin0))
        pServer = "server1";
    else
        pServer = "server2";

    ...

    snprintf (msg, 75, "up");
    client.publish (*pServer, msg);  //Uses variable set above (hopefully)
}

This:

char mediacenter = "server1";

should be:

char mediacenter[] = "server1";

If server really is of type String the proper syntax would be:

if (switchState0 == LOW) {
  server = "server1";
} else {
  server = "server2"; }
snprintf (msg, 75, "up");
client.publish(digitalRead(switchPin0) ? "server1" : "server2", msg); 

Even better...

Publish expects the topic in a char array. Not a String.

char mediacenter = "server1";
is not the same as
String(server) = "server1";

That passes one character pointed to by pServer, you want

 client.publish (pServer, msg);  //Uses variable set above (hopefully)

a7

1 Like

Think that did it - Thanks for replies!

What did it? Amplify the solution for the next person searching for the same issue.