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
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);
-
I've ended up using String(PaletteBrightness); And it seems to do the trick. Would it be better to use itoa()?Nah– Nah2016年09月11日 18:25:42 +00:00Commented 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– Majenko2016年09月11日 18:44:40 +00:00Commented 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– Nah2016年09月11日 22:54:28 +00:00Commented 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.Roberto Lo Giacco– Roberto Lo Giacco2016年09月12日 00:38:44 +00:00Commented 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– Nah2016年09月12日 13:03:26 +00:00Commented Sep 12, 2016 at 13:03