0

I'm working on a remote control code for ESP controller. Using ESPwebserver and Fastled. When I try to return a value of an uint8_t, as a POST response, i got strange result here is the relevant code:

uint8_t PaletteBrightness = 255; 

server.on("/Sync", HTTP_POST, []() {
String Sync = "PaletteBrightness:" + PaletteBrightness;
    Sync += ":end";
    Serial.println(Sync);
    server.send(200, "text/plain", Sync);
  });

The code complies, and runs fine but the result of 'Sync' in both serial, and POST response is:

Phase:end

Why? What does even Phase mean?
What I want is:

PaletteBrightness:255:end

Where the 255 is the value of 'uint8_t PaletteBrightness' Also, there will be more values, to add the 'Sync' string. Just trying to get one right.

1 Answer 1

0

You should convert your number uint8_t into it's ASCII representation before appending it to your string, otherwise you are appending just one character using it's byte representation.

To do so you can use a standard function itoa() which has a decent documentation available here.

So change line

 String Sync = "PaletteBrightness:" + PaletteBrightness;

into

 char buffer [4];
 String Sync = "PaletteBrightness:" + itoa(PaletteBrightness, buffer, 10);
7
  • I've ended up using String(PaletteBrightness); And it seems to do the trick. Would it be better to use itoa()?
    – Nah
    Sep 11, 2016 at 18:25
  • Avoid the use of String at all costs unless there absolutely no alternative. hackingmajenkoblog.wordpress.com/2016/02/04/…
    – Majenko
    Sep 11, 2016 at 18:44
  • Will read this trough. I need to send and receive data from client which is done in http post, effectively plain text. Don't think there is a way around strings there.
    – Nah
    Sep 11, 2016 at 22:54
  • Yes, there is at least another way: array of chars. And before you ask, strings are not just array of chars, remember you are dealing with C here, not Java or JavaScript. Also memory is a big constraint, anything that is dynamically allocated must be strictly controlled and memory fragmentation can quickly become an issue. Sep 12, 2016 at 0:38
  • Okay, I read up on String, and now i understand a bit better why are they bad. However, ESP8266WebServer.h Uses lots of Strings, and related String object functions. Isnt that also wrong? or I'm missing some key elements here.
    – Nah
    Sep 12, 2016 at 13:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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