israellot / esp-ginx

HTTP server for the ESP8266
MIT License
190 stars 46 forks source link

cJSON floating point issue #4

Open flo90 opened 9 years ago

flo90 commented 9 years ago

Hi, i tried your code today and its working very well but cJSON is not converting a float number correctly. You hit the problem if you try to read the dht22. The output looks like this: { "temp": %.0f, "hum": %.0f } My current fix is to typecast the values like this: cJSON_AddNumberToObject(root,"temp",(int8_t)data.dht22.temp); cJSON_AddNumberToObject(root,"hum",(uint8_t)data.dht22.hum); Maybe someone know how to fix the cJSON lib easily?!

I am using the esp-open-sdk (espressif lib v1.0.1) to compile the code.

israellot commented 9 years ago

The problem is the format specified in the sprintf. Our printf doesn't process the %.0f. The solution is quite simple.

israellot commented 9 years ago

I've just pushed a commit that should fix it. Thank you.

flo90 commented 9 years ago

Hi, this didn't fix the problem because it seems that the os_sprintf just doesn't support float. In the debug output c_sprintf is used. I replaced sprintf with c_sprintf. It's working now but a little bit dirty: { "temp": 22.200000762, "hum": 45.900001525 } Furthermore sometimes there is a big whitespace between "hum": and the number. I can't show it because github removes the whitespace.

The javascript removes the waste but it's not the best solution i think.

israellot commented 9 years ago

Can you check if changing

#ifndef sprintf
#define sprintf os_sprintf
#endif

to

#ifndef sprintf
#define sprintf c_sprintf
#endif

solves the problem?

flo90 commented 9 years ago

Hi, this just leads to the same result because the preprocessor replaces sprintf with c_sprintf. I think it's just a bad/simple float implementation. I have two ideas to fix this special case. The sensor throws the temperature as well as the humidity as a integer number e.g 22.3°C is represented as 223. Now you can convert this value to a string and send it to the browser wich could divide the number by 10. Or you just manipulate the string and add the dot between 22 and 3.