Using MATLAB with a Adafruit MPL3115A2 breakout board.

So this isn’t the most elegant, nor the cleanest code for working working with the Adafruit MPL3115A2 Breakout board, but it does work to read altitude and temperature.

Feel free to librarify, alter, or otherwise repost the code here.  It’s for educational purposes and those who might have a need to read temperature and altitude from an Arduino hooked up through MATLAB.  🙂 . Enjoy…


% Define constants

% Instantiate an Arduino instance.
a = arduino()
addrs = scanI2CBus(a)
mpl3115 = i2cdev(a, '0x60')

data = readRegister(mpl3115, MPL3115A2_WHOAMI, 'uint8');
if (data == 196)
    s0 = 'i2c Bus confirms presence of MPL3115A2 sensor module.\n';
    s0 = 'i2c Bus does NOT confirm the presence of MPL3115A2 sensor module.\n';

% Setup Altimeter Sensor
writeRegister(mpl3115, hex2dec('26'), hex2dec('b9'), 'uint8');

% Setup Temperature Sensor
writeRegister(mpl3115, hex2dec('13'), hex2dec('07'), 'uint8');

    % pull the status bits to see if we have valid measurements.
    status = readRegister(mpl3115, hex2dec('00'), 'uint8');
    % TODO: add validation for temp read ready.

    temperature = readRegister(mpl3115, hex2dec('04'), 'uint16');
    temp = ((bitshift(temperature, -4) / 16.0) * 9/5) + 32;
    s1 = 'Current Temperature in F: %d\n';
    fprintf(s1, temp);

    % TODO: add validation for altitude read ready.
    altitude1 = readRegister(mpl3115, hex2dec('01'), 'uint8');
    altitude2 = readRegister(mpl3115, hex2dec('02'), 'uint8');
    altitude3 = readRegister(mpl3115, hex2dec('03'), 'uint8');

    % Compose a valid 32 bit value from the 3 register reads.
    alt1 = bitshift(uint32(altitude1),16);
    alt2 = bitshift(uint32(altitude2),8);
    alt3 = uint32(altitude3);

    % now merge the bit shifted registers.
    alth = bitor(alt1,alt2);
    altl = alt3;
    alt = bitor(alth,altl);

    % Shift the bits down and divide to get ft above sea level.
    alt = (bitshift(alt, -4) / 16.0);

    % Output.
    s2 = 'Current Altitude %5d\n';
    fprintf(s2, alt);

    % Wait 5 seconds.



Phorkus is just this guy...

Posted in Hardware Hacking, MATLAB

Leave a Reply

Your email address will not be published. Required fields are marked *