Novedad: el cortafuegos de IA supervisa toda la plataforma y explica cada incidente con palabras sencillas. Vea cómo funciona

snprintf on a Nano prints ? instead of my float when building the JSON payload

snprintf on a Nano prints ? instead of my float when building the JSON payload

Resuelto 4 3

Mostly do ARM/ESP32, so the AVR side surprised me. Nano (ATmega328P) with an SHT31 and a W5500 Ethernet module, publishing to Hermetry with PubSubClient. I build the payload like I always do:

char buf[96];
snprintf(buf, sizeof(buf), "{"temp_c":%.2f,"rh":%.1f,"seq":%lu}", t, h, seq);
mqtt.publish("v1/telemetry", buf);

Serial shows {"temp_c":?,"rh":?,"seq":1043}, and Hermetry doesn’t store anything from it, which makes sense because that’s not JSON. I don’t want to pull String concatenation in on a 2 KB RAM chip. What’s the usual way?

♥ 1

is it a printf setting in the IDE? I think there’s a flag for floats somewhere

♥ 0

Liam’s half right. avr-libc’s printf family is built without float support by default to save flash, so %f prints ?. You can link the float version (-Wl,-u,vfprintf -lprintf_flt) but it costs about 1.5 KB of flash and the Arduino IDE makes the flags annoying.

What I do on Nanos is convert the floats with dtostrf first, then format strings:

char ts[8], hs[8], buf[96];
dtostrf(t, 0, 2, ts);      // width 0 = no padding
dtostrf(h, 0, 1, hs);
snprintf(buf, sizeof(buf), "{"temp_c":%s,"rh":%s,"seq":%lu}", ts, hs, seq);

Or send integers: temp_c10 as 2154 and scale it back later. Same quota, zero float formatting. Also check for NaN when the SHT31 read fails: dtostrf prints nan, which isn’t valid JSON, and the whole message gets stored as raw text. Skip the key when the read fails.

Timestamps in UTC or it didn't happen.
Solución aceptada♥ 5

dtostrf it is. Valid JSON now, keys showing up. The NaN point bit me ten minutes later when I unplugged the sensor to test, so good call.

♥ 0

oh nice, didn’t know about dtostrf at all

♥ 0
Viendo 5 entradas – de la 1 a la 5 (de un total de 5)
  • Debes estar registrado para responder a este debate.

Únete a la conversación

Inicia sesión para preguntar y responder, dar me gusta a las publicaciones útiles y marcar la respuesta que resolvió tu problema. Cada aportación suma puntos y niveles.

Compartir