Los floats salen como basura cuando mi Uno lee un Nano por I2C
Traducido del English por IA ·
Controlador de invernadero, dos placas: un Nano lee sondas de suelo y un DS18B20 y actúa como esclavo I2C en 0x08; un Uno es el maestro, recoge los datos del Nano y los envía por serie a un ESP32 que publica en Hermetry. Los enteros (humedad en bruto, 0-1023) llegan bien. El float de temperatura llega como valores absurdos como -2.3e-38 o nan, y Hermetry rechaza la clave siempre que es NaN, así que el gráfico tiene huecos.Lado esclavo:
void onRequest() {
Wire.write(moisture1 >> 8); Wire.write(moisture1 & 0xFF);
Wire.write(moisture2 >> 8); Wire.write(moisture2 & 0xFF);
Wire.write((byte)tempC); // tried this first, lost decimals
Wire.write((byte*)&tempC, 4);
}
El maestro hace Wire.requestFrom(8, 9) y lee los bytes de vuelta en las mismas variables.
Greenhouse controller, two boards: a Nano reads soil probes and a DS18B20 and acts as I2C slave at 0x08; an Uno is master, collects from the Nano and passes everything over serial to an ESP32 that publishes to Hermetry. The ints (moisture raw, 0-1023) come through fine. The temperature float arrives as nonsense like -2.3e-38 or nan, and Hermetry refuses the key whenever it’s NaN, so the chart has holes.
Slave side:
void onRequest() {
Wire.write(moisture1 >> 8); Wire.write(moisture1 & 0xFF);
Wire.write(moisture2 >> 8); Wire.write(moisture2 & 0xFF);
Wire.write((byte)tempC); // tried this first, lost decimals
Wire.write((byte*)&tempC, 4);
}
Master does Wire.requestFrom(8, 9) and reads bytes back into the same variables.
Traducido del English por IA ·
¿Podrías enviarlo como cadena y analizarlo en el otro extremo? Eso es lo que hice para el serie.
Could you send it as a string and parse it on the other end? That’s what I did for serial.
Traducido del English por IA ·
Las cadenas por I2C desperdician bytes y solo obtienes 32 por transferencia. Muestra el lado del master, apuesto a que ahí es donde se rompe.
Strings over I2C waste bytes and you only get 32 per transfer. Show the master side, I bet that’s where it breaks.
Traducido del English por IA ·
Lado master, perdón, debí incluirlo:
Wire.requestFrom(8, 9);
m1 = (Wire.read() << 8) | Wire.read();
m2 = (Wire.read() << 8) | Wire.read();
Wire.read(); // the old byte
for (int i = 0; i < 4; i++) ((byte*)&t)[i] = Wire.read();
master side, sorry, should have included it:
Wire.requestFrom(8, 9);
m1 = (Wire.read() << 8) | Wire.read();
m2 = (Wire.read() << 8) | Wire.read();
Wire.read(); // the old byte
for (int i = 0; i < 4; i++) ((byte*)&t)[i] = Wire.read();
Traducido del English por IA ·
Siguiendo el hilo, tengo planeada una configuración similar para el invernadero de nuestro hotel.
Following, I have a similar setup planned for our hotel greenhouse.
Traducido del English por IA ·
Dos errores, y un tercero esperando a ocurrir. Hice casi exactamente lo mismo en un banco de pruebas hace años.1. En el esclavo, cada Wire.write() dentro de onRequest en AVR reemplaza el búfer en lugar de añadir a él en algunas versiones de la biblioteca, y el orden de evaluación de (Wire.read() << 8) | Wire.read() en el maestro no está definido en C++, así que los bytes pueden llegar intercambiados.2. El byte suelto de más desplaza todo si alguna vez los conteos no coinciden.Hágalo con una estructura en ambos lados y una sola escritura:
struct __attribute__((packed)) Packet {
uint16_t m1, m2;
int16_t t_x100; // 23.47 C -> 2347, no float on the wire
uint8_t seq;
};
// slave
void onRequest() { Wire.write((uint8_t*)&pkt, sizeof(pkt)); }
// master
Packet p;
if (Wire.requestFrom(8, sizeof(p)) == sizeof(p))
Wire.readBytes((uint8_t*)&p, sizeof(p));
float t = p.t_x100 / 100.0;
Los enteros escalados evitan cualquier duda sobre la disposición de los floats si el esclavo acaba siendo un ESP o un STM32. El byte seq le indica si está leyendo un paquete obsoleto. Y en el lado del ESP32, omita la clave por completo si una lectura no es válida en lugar de enviar NaN; de todos modos NaN no es JSON válido.
Two bugs, and a third waiting to happen. I did nearly this exact thing on a test rig years ago.
1. On the slave, each Wire.write() inside onRequest on AVR replaces the buffer instead of adding to it in some library versions, and the order of evaluation in (Wire.read() << 8) | Wire.read() on the master isn’t defined in C++, so the bytes can come out swapped.
2. The stray single byte shifts everything if the counts ever disagree.
Do it with one struct on both sides and one write:
struct __attribute__((packed)) Packet {
uint16_t m1, m2;
int16_t t_x100; // 23.47 C -> 2347, no float on the wire
uint8_t seq;
};
// slave
void onRequest() { Wire.write((uint8_t*)&pkt, sizeof(pkt)); }
// master
Packet p;
if (Wire.requestFrom(8, sizeof(p)) == sizeof(p))
Wire.readBytes((uint8_t*)&p, sizeof(p));
float t = p.t_x100 / 100.0;
Scaled integers avoid any float layout question if the slave ever becomes an ESP or an STM32. The seq byte tells you if you’re reading a stale packet. And on the ESP32 side, skip the key entirely if a reading is invalid instead of sending NaN, NaN isn’t valid JSON anyway.
Traducido del English por IA ·
Un struct con int escalado lo arregló. La temperatura está limpia desde ayer por la tarde, sin huecos en el gráfico. Lo del orden de evaluación no lo sabía.
Struct with scaled int fixed it. Temperature has been clean since yesterday afternoon, no gaps on the chart. The evaluation order thing was news to me.
- 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.

