1

How would you send a struct from an i2c slave when requested by an i2c master?

Slave Struct Respdonder Sketch (Seeeduino Xiao)

#include <Wire.h>
struct TransmitData
{
 int a;
 int b;
 int c;
 int d;
 float e;
 float f;
 float g;
 float h;
};
TransmitData data;
void setup()
{
 Serial.begin(9600);
 Wire.begin(2);
 Wire.onRequest(requestEvent);
 data.a = 1;
 data.b = 2;
 data.c = 3;
 data.d = 4;
 data.e = 5.1;
 data.f = 6.1;
 data.g = 7.1;
 data.h = 8.1;
}
void loop()
{
 delay(100);
}
void requestEvent()
{
 Serial.print("sending ("); Serial.print(sizeof data); Serial.println(" bytes)");
 Wire.write((byte *)&data, sizeof data);
}

Master Struct Requester/Reciever Sketch (Arduino MEGA)

#include <Wire.h>
struct TransmitData
{
 int32_t a;
 int32_t b;
 int32_t c;
 int32_t d;
 float e;
 float f;
 float g;
 float h;
};
TransmitData data;
void setup() {
 Wire.begin();
 Serial.begin(9600);
}
void loop() {
 Serial.print("requesting ("); Serial.print(sizeof data); Serial.print(" bytes)... ");
 if (Wire.requestFrom(2, sizeof data)) {
 Wire.readBytes((byte*) &data, sizeof data);
 Serial.println("done");
 Serial.println(data.a);
 Serial.println(data.b);
 Serial.println(data.c);
 Serial.println(data.d);
 Serial.println(data.e);
 Serial.println(data.f);
 Serial.println(data.g);
 Serial.println(data.h);
 } 
 else {
 Serial.println("could not connect");
 }
 delay(500);
}

The serial output on the slave device is:

sending (32 bytes)

The serial output on the master device is:

requesting (24 bytes)... done
1
0
2
0
0.00
0.00
5.10
6.10
asked May 11, 2021 at 13:29
1
  • You can try the I2C_Anything library by Nick Gammon Commented May 11, 2021 at 13:53

1 Answer 1

2

int isn't guaranteed to be the same size across platforms. Use fixed width integer types instead.

https://en.cppreference.com/w/cpp/types/integer

struct TransmitData
{
 int32_t a;
 int32_t b;
 int32_t c;
 int32_t d;
 float e;
 float f;
 float g;
 float h;
};
answered May 11, 2021 at 13:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.