Yeni: Yapay zekâ güvenlik duvarı tüm platformu izliyor ve her olayı sade bir dille açıklıyor. Nasıl çalıştığını görün

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

Çözüldü 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.
Kabul edilen çözüm♥ 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
5 yazı görüntüleniyor – 1 ile 5 arası (toplam 5)
  • Bu konuyu yanıtlamak için giriş yapmış olmalısınız.

Sohbete katılın

Soru sormak ve yanıtlamak, yararlı gönderileri beğenmek ve sorununuzu çözen yanıtı işaretlemek için oturum açın. Her katkı puan ve seviye kazandırır.

Paylaş