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
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;
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.