Source code and configuration used in my function:
I include all headers in the Libraries panel of S-Function Builder,
#ifndef MATLAB_MEX_FILE
#define ARDUINO 100
#include <Arduino.h>
#include <Wire.h>
#include <Wire.cpp>
#include <twi.h>
#include <twi.c>
#define MPU 0x68
#endif
Wire.* and twi.* files are copied from Arduino IDE's directory. I put these files along with my S-Function block file.
The address of I2C is 0x68 here.
Next, the code for sensor outputs are placed in Outputs panel. And do not forget to add ports in Data Properties panel.
#ifndef MATLAB_MEX_FILE
Wire.beginTransmission(MPU);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(MPU, 14, true);
int raw = Wire.read() << 8;
raw = raw | Wire.read();
ax[0] = (float)raw / 8192.0f;
raw = Wire.read() << 8;
raw = raw | Wire.read();
ay[0] = (float)raw / 8192.0f;
raw = Wire.read() << 8;
raw = raw | Wire.read();
az[0] = (float)raw / 8192.0f;
raw = Wire.read() << 8;
raw = raw | Wire.read();
temp[0] = (float)raw / 340.0f + 36.53f;
raw = Wire.read() << 8;
raw = raw | Wire.read();
gx[0] = (float)raw / 131.0f;
raw = Wire.read() << 8;
raw = raw | Wire.read();
gy[0] = (float)raw / 131.0f;
raw = Wire.read() << 8;
raw = raw | Wire.read();
gz[0] = (float)raw / 131.0f;
#endif
Finally, initialization and configuration are done in Discrete Update panel.
#ifndef MATLAB_MEX_FILE
if (xD[0] != 1) {
Wire.begin();
/* Do not sleep */
Wire.beginTransmission(MPU);
Wire.write(0x6B);
Wire.write(0);
Wire.endTransmission(true);
/* Gyroscope full scale range: 250 degs/s */
Wire.beginTransmission(MPU);
Wire.write(0x1B);
Wire.write(0);
Wire.endTransmission(true);
/* Accelerometer full scale range: 4g */
Wire.beginTransmission(MPU);
Wire.write(0x1C);
Wire.write(8);
Wire.endTransmission(true);
xD[0] = 1;
}
#endif
Please refer to your board's datasheet for specific address and LSB scales. I am using GY-521 here.