Uno como esclavo I2C enviando flotantes a un Mega y recibiendo comandos: los valores llegan alterados
Traducido del English por IA ·
Otra vez yo. Proyecto de jardín: un Uno en el cobertizo lee la humedad del suelo, la temperatura y un caudalímetro de agua. Un Mega en la misma caja tiene el puente Ethernet a Wi-Fi y envía todo a Hermetry. Quiero que el Mega pida al Uno sus lecturas por I2C y, a veces, le diga que abra la válvula de riego (el relé de la válvula está en el Uno).Uno (esclavo, dirección 8):
void requestEvent() {
Wire.write(String(moisture).c_str());
Wire.write(String(tempC).c_str());
Wire.write(String(flowLpm).c_str());
}
Mega:
Wire.requestFrom(8, 12);
while (Wire.available()) Serial.print((char)Wire.read());
Lo que obtengo son cosas como 4312.5 y ÿÿÿ mezcladas, y a veces solo el primer valor. Para la válvula ni siquiera he empezado; no sé cómo recibe el esclavo un comando.
Me again. Garden project: an Uno out in the shed reads soil moisture, temperature and a water flow meter. A Mega in the same box has the Ethernet-to-Wi-Fi bridge and sends everything on to Hermetry. I want the Mega to ask the Uno for its readings over I2C, and sometimes tell it to open the irrigation valve (the valve relay is on the Uno).
Uno (slave, address 8):
void requestEvent() {
Wire.write(String(moisture).c_str());
Wire.write(String(tempC).c_str());
Wire.write(String(flowLpm).c_str());
}
Mega:
Wire.requestFrom(8, 12);
while (Wire.available()) Serial.print((char)Wire.read());
What I get is things like 4312.5 and ÿÿÿ mixed together, and sometimes only the first value. For the valve I haven’t even started, I don’t know how the slave gets a command.
Traducido del English por IA ·
A continuación, tengo exactamente el mismo problema de ÿÿÿ con dos placas.
Following, I have the exact same garbled ÿÿÿ thing with two boards.
Traducido del English por IA ·
Quizás necesitas resistencias pull-up en SDA y SCL. Leí que I2C las necesita.
Maybe you need pull-up resistors on SDA and SCL? I read I2C needs them.
Traducido del English por IA ·
Ambas placas funcionan a 5 V y la biblioteca Wire activa las resistencias pull-up internas del AVR, así que en cables cortos dentro de una misma caja no es ese el problema. El problema mayor son las tres llamadas a Wire.write en requestEvent. En AVR solo una escritura por petición funciona de forma fiable, y las cadenas de texto de longitud desconocida empeoran las cosas. Pon los valores en un único buffer y escríbelo una vez. Y nada de impresión por Serial dentro de los manejadores.
Both boards are 5 V and the Wire library turns on the AVR’s internal pull-ups, so on short wires in one box that’s not it. The bigger problem is three Wire.write calls in requestEvent. Only one write per request works reliably on AVR, and text strings of unknown length make it worse. Put the values in one buffer and write it once. And no Serial printing inside the handlers.
Traducido del English por IA ·
Lo que dijo Carlos, aquí tienes la versión que uso para nuestros contadores de línea (un Uno que cuenta y una placa más grande que se encarga de la red). Enviar binario, tamaño fijo, en una sola struct, y usar onReceive para los comandos.Struct compartida, en ambos sketches:
struct Reading {
int16_t moisture; // raw ADC
int16_t temp_x10; // 21.5 C -> 215
int16_t flow_x10; // L/min x10
};
Uno (esclavo):
volatile Reading r;
volatile bool openValve = false;
void requestEvent() { Wire.write((const uint8_t*)&r, sizeof(r)); } // one write
void receiveEvent(int n) { if (Wire.available()) openValve = Wire.read() == 1; }
void setup() { Wire.begin(8); Wire.onRequest(requestEvent); Wire.onReceive(receiveEvent); }
void loop() {
Reading tmp = { readMoisture(), (int16_t)(readTemp() * 10), (int16_t)(readFlow() * 10) };
noInterrupts(); r = tmp; interrupts();
digitalWrite(VALVE_PIN, openValve);
}
Mega (maestro):
Reading r;
if (Wire.requestFrom(8, (int)sizeof(r)) == sizeof(r)) Wire.readBytes((uint8_t*)&r, sizeof(r));
float tempC = r.temp_x10 / 10.0;
Wire.beginTransmission(8); Wire.write(1); Wire.endTransmission(); // open valve
Ambas son AVR, así que el orden de bytes y los tamaños de int coinciden, y la struct viaja tal cual. La ÿ que viste es 0xFF, lo que lee el maestro cuando el esclavo no tiene nada más que enviar. Pedir exactamente sizeof(r) también soluciona eso.
What Carlos said, here’s the version I use for our line counters (an Uno doing the counting, a bigger board doing the network). Send binary, fixed size, in one struct, and use onReceive for commands.
Shared struct, in both sketches:
struct Reading {
int16_t moisture; // raw ADC
int16_t temp_x10; // 21.5 C -> 215
int16_t flow_x10; // L/min x10
};
Uno (slave):
volatile Reading r;
volatile bool openValve = false;
void requestEvent() { Wire.write((const uint8_t*)&r, sizeof(r)); } // one write
void receiveEvent(int n) { if (Wire.available()) openValve = Wire.read() == 1; }
void setup() { Wire.begin(8); Wire.onRequest(requestEvent); Wire.onReceive(receiveEvent); }
void loop() {
Reading tmp = { readMoisture(), (int16_t)(readTemp() * 10), (int16_t)(readFlow() * 10) };
noInterrupts(); r = tmp; interrupts();
digitalWrite(VALVE_PIN, openValve);
}
Mega (master):
Reading r;
if (Wire.requestFrom(8, (int)sizeof(r)) == sizeof(r)) Wire.readBytes((uint8_t*)&r, sizeof(r));
float tempC = r.temp_x10 / 10.0;
Wire.beginTransmission(8); Wire.write(1); Wire.endTransmission(); // open valve
Both are AVR, so byte order and int sizes match and the struct goes across as-is. The ÿ you saw is 0xFF, what the master reads when the slave has nothing left to send. Asking for exactly sizeof(r) fixes that too.
Traducido del English por IA ·
Funciona a la primera, algo que nunca me pasa. Las lecturas son limpias y la válvula se abre cuando el Mega envía un 1. Estaba enviando texto porque pensaba que I2C era «como Serial». Además, aproveché para corregir mi payload de Hermetry: la temperatura ahora se envía como un número con un decimal.
Works first time, which never happens to me. Readings are clean and the valve opens when the Mega sends 1. I’d been sending text because I thought I2C was «like Serial». Also fixed my Hermetry payload while I was at it: temperature now goes out as a number with one decimal.
- 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.

