MATLAB Examples

Control LSM303 IMU Sensor

This example shows how to use the MATLAB® Support Package for Arduino® Hardware to control a three axis LSM303 accelerometer and magnetometer.


Hardware Requirements

  • Arduino board
  • LSM303 breakout board with I2C interface

Hardware Setup

  • Connect SDA pin on LSM303 board to SDA pin on Arduino board.
  • Connect SCL pin on LSM303 board to SCL pin on Arduino board.
  • Connect VIN pin on LSM303 board to 5V pin on Arduino board.
  • Connect GND pin on LSM303 board to GND pin on Arduino board.

Create Arduino Object with Pololu/LSM303 Add-On

a = arduino('COM38', 'Uno', 'Libraries', 'Pololu/LSM303')
a = 

  arduino with properties:

                    Port: 'COM38'
                   Board: 'Uno'
           AvailablePins: {'D2-D13', 'A0-A5'}
               Libraries: {'I2C', 'Pololu/LSM303'}

Read Data from LSM303 Device

Create LSM303 device object for LSM303D accelerometer and magnetometer.

compass = addon(a, 'Pololu/LSM303')
compass = 

  LSM303 with properties:

               Pins: 'A4'(SDA), 'A5'(SCL)
                Bus: 0
         I2CAddress: 29 (0x1D)
         DeviceType: 'D'
        SA0PinState: 'auto'

Read acceleration and magnetization.

acc = readAcceleration(compass);
fprintf('Acceleration: %+.3f(X) %+.3f(Y) %+.3f(Z) (m/s^2)\n', acc(1), acc(2), acc(3));
'Acceleration: +0.252(X) -10.040(Y) +1.373(Z) (m/s^2)

Calculate magnetic compass heading in degrees from x and y readings by holding the magnetometer flat in an open area.

mag = readMagneticField(compass);
heading = (atan2(mag(2), mag(1))*180)/pi;
if heading < 0
    heading = heading + 360; % normalize to 0-360
fprintf('Magnetic field strength: %+.3f(X) %+.3f(Y) %+.3f(Z) (uT)    Heading: %.1f (degrees)\n', ...
    mag(1), mag(2), mag(3), heading);
Magnetic field strength: +5.920(X) +48.608(Y) +1.712(Z) (uT)    Heading: 83.1 (degrees)

Clean Up

clear compass
clear a