snprintf en un Nano imprime ? en lugar de mi float al construir el payload JSON
Traducido del English por IA ·
Trabajo sobre todo con ARM/ESP32, así que el lado AVR me sorprendió. Nano (ATmega328P) con un SHT31 y un módulo Ethernet W5500, publicando en Hermetry con PubSubClient. Construyo el payload como siempre:
char buf[96];
snprintf(buf, sizeof(buf), "{"temp_c":%.2f,"rh":%.1f,"seq":%lu}", t, h, seq);
mqtt.publish("v1/telemetry", buf);
El monitor serie muestra {"temp_c":?,"rh":?,"seq":1043}, y Hermetry no almacena nada de eso, lo cual tiene sentido porque eso no es JSON. No quiero incluir concatenación de String en un chip con 2 KB de RAM. ¿Cuál es la forma habitual de hacerlo?
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?
Traducido del English por IA ·
¿Es una configuración de printf en el IDE? Creo que hay un flag para floats en algún lugar
is it a printf setting in the IDE? I think there’s a flag for floats somewhere
Traducido del English por IA ·
Liam tiene medio razón. La familia printf de avr-libc se compila sin soporte de float por defecto para ahorrar flash, así que %f imprime ?. Puedes enlazar la versión con float (-Wl,-u,vfprintf -lprintf_flt), pero cuesta unos 1.5 KB de flash y el IDE de Arduino hace incómodas las banderas.
Lo que hago en los Nano es convertir primero los floats con dtostrf y luego formatear las cadenas:
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);
O envía enteros: temp_c10 como 2154 y luego lo vuelves a escalar. Mismo cupo, cero formateo de float. Además, verifica si hay NaN cuando falla la lectura del SHT31: dtostrf imprime nan, que no es JSON válido, y todo el mensaje se guarda como texto sin formato. Omite la clave cuando la lectura falle.
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.
Traducido del English por IA ·
Pues dtostrf. JSON válido ahora, las claves aparecen. El tema de NaN me pilló diez minutos después, cuando desconecté el sensor para probar, así que buen consejo.
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.
Traducido del English por IA ·
Oh, genial, no conocía dtostrf para nada
oh nice, didn’t know about dtostrf at all
- 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.

