Plotting Accelerometer Vectors with Matlab and Arduino/April 12, 2016by Ryan Morrison

Since familiarizing myself with MATLAB via an online course, many of my thoughts have centered around how I can utilize it for my own purposes. While currently drafting a new project involving machine vision, the utility of MATLAB has become obvious. In preparation for that project, I am going to perform a series of exploratory exercises using Arduino, Raspberry Pi, sensors, and MATLAB. As such, this is a first in several posts detailing my experiments.

For this first exercise, the goal is to get the Arduino Uno and MATLAB communicating and graphically display the results. In addition to the great resources found on the MATLAB website, I found a good set of examples detailing MATLAB/Arduino interfacing at matlabarduino.org. The steps are as follows:

1. Connect Arduino to accelerometer — I am using the LSM303DLHC.
2. Write/upload a sketch that reads the accelerometer and prints the values to the serial port.
3. Write MATLAB code that reads values from the serial port and plots them as vectors in 3D space.

Arduino and LSM303dlhc

For those unfamiliar with using accelerometers with Arduino, Adafruit provides library links, code explanations, and assembly/connection instructions for the LSM303DLHC. Below is my setup, which stabilizes the board/accelerometer and allows for rotating/manipulating the rig in 3D space.

Arduino Uno and LSM303DLHC accelerometer.

Serial Communication between Arduino and matlab

The complete code for this exercise is available on my matlab-arduino repo. The snippets below show the handshake between Arduino and MATLAB, which verifies that serial data is being sent/received on both ends. First, MATLAB waits for Arduino to send 'a' to the serial port, and then notifies the user that serial data is being received:

% handshake btwn matlab & serial device
a = 'b';
while(a ~= 'a')
end
if(a == 'a')
end
fprintf(obj.dev,'%c','a');
mbox = msgbox('Serial Communication setup.'); uiwait(mbox);
fscanf(obj.dev,'%u');

On the Arduino side, the setup() function prints 'a' to the serial port and waits for MATLAB to send a response:

// handshake between arduino and serial port
Serial.println('a');
char a = 'b';
while(a != 'a') {
}

Once the handshake between Arduino and MATLAB has completed, we enter the loop() function, read the accelerometer, and print to the serial port.

if(Serial.available() > 0) {
if(mode == 'R') {
sensors_event_t accelEvent;
accel.getEvent(&accelEvent);
accelRead = accelEvent.acceleration.x * scaleG;
accelRead = accelEvent.acceleration.y * scaleG;