Const String to String issues

Im trying to receive mqtt data and write this to software serial to communicate with the serial connection on my spapool from a nodemcu but am having issues with this conversion.

void onConnectionEstablished() {

  client.subscribe("/spanet/serialdata/rx", [] (const String &payload)  {
    Serial.println(payload);
    swSer.write(payload);
    if (payload == "RF") {swSer.write("RF\n");}
    if (payload == "S24:1") {swSer.write("S24:1\n");}
    if (payload == "S24:0") {swSer.write("S24:0F\n");}
  });

I get error during compile "no matching function for call to 'SoftwareSerial::write(const String&)'
on this line swSer.write(payload);

The if statements work fine but i would just like to send the RAW payload as a string as otherwise i will have to put an if statement for every option.

Any help would be great i have googled but cant find how to convert it to work.

use

swSer.write(payload.c_str());

https://www.cplusplus.com/reference/string/string/c_str/

Or use print instead of write

im unsure as to why but if i use print i dont get a serial response from the device but with write it works fine.

Thanks will try tonight.

@shanekuz , please get in the habit of using code tags when posting code on the forum; edit your post, select all code and click the </> button to apply so-called code tags and next save your post. It makes it easier to read, easier to copy and prevents the forum software from incorrect interpretation of the code.

So we e.g. don't have to look at [] but get a proper [] :wink:

1 Like

Thankyou Whandall this worked perfect. Can i ask how do i convert the other way?

I also need to read the string from the swSer.readstring but need to convert that so i can send via MQTT

Im reading the swSer fine and can print it to console but i need to publish this.

inString = swSer.readstring
client.publish("/spanet/serialdata/tx", inString);

Did you use print or println?

A simple assignment works for the other direction.

https://www.cplusplus.com/reference/string/basic_string/operator=/

I tried both as understand the \n need but nether works where are write works fine.

Thanks Whandall im all going now appreciate your help here.

1 Like

OK - that’s weird because it sends the same thing out if written the same way (print, not println) with a cString

I don't believe any of it. Not without seeing the full code. Software Serial inherits from Print. It knows how to print/println a 'const String' .

+1 with the disbelief.

print() absolutely would work, but for a String without embedded zeros it's just the same.

size_t Print::print(const String &s)
{
  return write(s.c_str(), s.length());
}

Probably the conversion before adds a strlen() call, but that's not a big deal IMHO.

Agreed. But when someone claims that a known-working feature "Doesn't Work", I suspect problems elsewhere in the (unposted) code.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.