Multiple i2c writes on request

Hi

i ve trying since houres. Maybe a very simple mistake that i just don't see but i am really going crazy

Just request from clients 4 floats values... send them as 4 Byte array, and output them on Server on Serial Output after converting Bytearrays to Float

Server

union u_tag {
   byte b[4];
   float fval;
  };

void clientRequest()    called in Loop
{
   Wire.requestFrom(8, 16);     // Request 16 bytes fromClient

   u_tag u1;   
   u1.b[0] = Wire.read(); 
   u1.b[1] = Wire.read();
   u1.b[2] = Wire.read();
   u1.b[3] = Wire.read();
   Serial.println(u1.fval);

   u_tag u2;
   u2.b[0] = Wire.read(); 
   u2.b[1] = Wire.read();
   u2.b[2] = Wire.read();
   u2.b[3] = Wire.read();
   Serial.println(u2.fval);
 
   u_tag u3;   
   u3.b[0] = Wire.read(); 
   u3.b[1] = Wire.read();
   u3.b[2] = Wire.read();
   u3.b[3] = Wire.read();
   Serial.println(u3.fval);
   
   u_tag u4;
   u4.b[0] = Wire.read(); 
   u4.b[1] = Wire.read();
   u4.b[2] = Wire.read();
   u4.b[3] = Wire.read();
   Serial.println(u4.fval);

}

Client

void requestEvent() {

  Wire.write((char*)&VOLTAGE1,sizeof(float)); 
  Wire.write((char*)&VOLTAGE2,sizeof(float));
  Wire.write((char*)&VOLTAGE3,sizeof(float));
  Wire.write((char*)&CURRENT,sizeof(float));
}

Serialoutput Server:

511.20 
nan
nan
nan


511.20 
nan
nan
nan

511.20 should be the last write value "CURRENT" from client.. but out put as first? if i decomment last write i already get that Value one bevore =>Voltage 3. but i never get all .. always just the last.. Any ideas????

Its should looks like that

Serialoutput Server:

12.52  
24.54
23.29
511.20 


12.52
24.54
23.29
511.20

regards
Peter

On the slave side, you need to place all the bytes to be sent in one buffer before sending it with Wire.write().

One way to do it is with a struct. Your receive sketch will work with this.

#include <Wire.h>

struct
{
  float Voltage1;
  float Voltage2;
  float Voltage3;
  float Current;
}
floatsToSend;

void requestEvent ()
{
  floatsToSend.Voltage1 = 12.52;
  floatsToSend.Voltage2 = 25.54;
  floatsToSend.Voltage3 = 23.29;
  floatsToSend.Current = 511.20;

  Wire.write((byte*)&floatsToSend, sizeof(floatsToSend));
}


void setup() {
  Wire.begin(8);
  Wire.onRequest(requestEvent);
}

void loop() {}

Thank you for response. Very good to know for next time

I already solved it one houre bevore with a workaround

First send ID of requested value to client and set ID in client
Second request value and client response value by ID set before

Server loop for each value

thanks peter