String variables - a little basic coding help needed


#1

Hi all,

I’m having trouble adapting some first draft code into a more flexible version that can be used on multiple devices. Below are two lines of code that I’m using successfully to send a message to a web hook which then processes a notification. This was fine for one unit, but soon I will have between 5 and 10 units, and I want to use a variable called TankName to change the name in the notification, without having custom code for each unit, there are a number of notifications for each TankName.
The issue is I’m having trouble changing the syntax to insert each mention of “CORNER TANK” (which is TankName in this instance) into my message as a variable.

I hope that makes sense, can anyone help me modify the code to use a variable here ?

Thanks!!
J

sprintf(message, “{“n”:”%s", “m”:“CORNER TANK just cameonline, CORNER TANK WATER LEVEL LOW!”}", cellNumber);
Particle.publish(webhookName, message);


#2

You just replace the tank name with another %s place holder in the format string and pass in a variable that holds the actual name - for two instances of the same name you need to do that twice


#3

Thanks, ScruffR
That did it! I was not really understanding the placeholders, which I now understand at least a little bit!
J


#4

I’m trying to add a boolean value to a Particle.publish using sprintf, I’ve simplified out the rest of the message as much as I can below:

I know that the sprintf line isn’t right to accomplish this, can anyone help me to get the right syntax to cast the Boolean value into the sprintf command? Please note that I’ve escaped the quotes around the %b, but I can’t figure out how to make that show up in the post.

I’m basically looking to get the particle.publish to issue the following data:
{“TRUE”} -or-
{“FALSE”}

const char webhookName[] = “DoorStatus”;
bool doorOpen;

sprintf(message, “{ “%b”}”, doorOpen);
Particle.publish(webhookName, message);


#5

Well, I’ll just go ahead and use the 1 or 0 that is cast from String(doorOpen).

I guess if I really need the TRUE or FALSE I’ll go ahead and make an if/else that changes the 0 or 1 to the text I need.

If anyone knows of a more elegant way to do it, please chime in! :slight_smile:
J


#6

There is no dedicated printf() placeholder for boolean but they are treated as integers.
If you don’t know what placeholders to use you can always look up the C++ reference about printf()

However, if you want to read TRUE/FALSE in your response, you can always go with a string.

  snprintf(str, sizeof(str), "%s", myBool ? "TRUE" : "FALSE");