Namaste!

Welcome to a blog about things in my life, observations about the world, and just silly stuff. Enjoy!

Monday, April 29, 2013

Matlab calling Arduino... are you there?

Matlab: "Hello, Arduino?"
Arduino: "Hello Matlab!"

This post gives an example of how to communicate between Matlab and the Arduino via a USB port (e.g. serial communication).  The accelerometers were purchased from Adafruit Inustries (discussed in another post) and connected to an Arduino Mega 2560.

Setup:
1. Connect the Arduino to your computer with the USB cable.
2. Make sure the sensor (i.e. accelerometer) is connected to the Arduino.
3. Open, compile, and upload the accelerometer sketch (discussed in a previous post).  The TX LED on the Arduino should blink every time it transmits data.
4. Open Matlab and create a new m file with the following code.  Alternatively, you could also copy and paste this into the command window and run the script there.

close all; clear all; clc
% create a serial port object called 's1' with a baud rate of 9600 (same as Arduino's sketch)
s1 = serial('/dev/tty.usbmodemfa131', 'BaudRate', 9600)
fopen(s1);
fprintf(s1, '*IND?')
ind = fscanf(s1)
% Read and display the data the Arduino is transmitting continuously in the command window
s1.TimerFcn=@(x,y)disp(char(fscanf(s1)))
% Close serial port when you want to stop displaying data in Matlab's command window
fclose(s1)

More to come...

No comments:

Post a Comment