MATLAB Answers

storing arduino serial data to cell array

조회 수: 156(최근 30일)
Ritter 1 Aug 2014
댓글: harold 14 May 2018
I have an Arduino Mega 2560 that reads and outputs raw the x, y and z accelerometer sensor values of 3 different acceleromters(shown below):
void loop()
int hip_x = analogRead(hip_xpin);
int hip_y = analogRead(hip_ypin);
int hip_z = analogRead(hip_zpin);
int knee_x = analogRead(knee_xpin);
int knee_y = analogRead(knee_ypin);
int knee_z = analogRead(knee_zpin);
int ankle_x = analogRead(ankle_xpin);
int ankle_y = analogRead(ankle_ypin);
int ankle_z = analogRead(ankle_zpin);
if(digitalRead(pulse)== LOW)
while (digitalRead(pulse)== LOW)
//do nothing
The Arduino is meant to synchronize with a motion capture system running at 60 frames per second and then take accelerometer values once per frame. I wrote a Matlab script to read and store the values into a cell array.
%clear all;
s1 = serial('COM9'); %define serial port
s1.BaudRate=115200; %define baud rate
%open serial port
%set(s1, 'terminator', 'LF');
s1.ReadAsyncMode = 'continuous';
count =1;
%data = cell(480,10);
%evalin('data', 's1');
while(s1.BytesAvailable <= 0) %wait until Arduino outputs data
while (1)
%while(s1.BytesAvailable > 0)
data = fscanf(s1); %read sensor
%count = count+1;
% end
% close the serial port!
However no matter how I play with the 'fscanf' function to store the incoming values into an array I keep getting a dimension mismatch error. When I display the incoming serial values I get this:
515 511 620 515 514 622 502 495 624
515 511 620 515 514 622 502 495 624
corresponding to the x, y and z values of each acceleromter respectively. I would like to keep this format but have Matlab store it in a cell array for further processing. Can anyone explain how I may accomplish this?

  댓글 수: 0

로그인 to comment.


Juan B. Gutierrez
Juan B. Gutierrez 4 Apr 2015
Ritter, it has been a few months since you asked this, but I ran into it yesterday. The trick is to know that the serial gives you a string, and you have to split it using strsplit. Here is a solution:
In your Arduino code, send the values separated by tab (any other character works as well):
// print a tab character:
Serial.print("\t"); // Use this character in MATLAB
The following MATLAB code loads it into a matrix:
sFile = 'AcceDualAxis.csv';
if exist(sFile) == 0 ; % if the file does not exists, read instrumentation
delete(instrfindall); %pre-emptively close all ports
s1 = serial('COM5'); %define serial port to read the Arduino
s1.BaudRate=115200; %define baud rate
s1.ReadAsyncMode = 'continuous';
while(s1.BytesAvailable <= 0) %wait until Arduino outputs data
mData = [];
for i=1:1000 %while if constant acquisition is needed.
sSerialData = fscanf(s1); %read sensor
t = strsplit(sSerialData,'\t'); % same character as the Arduino code
mData(i,1) = str2double(t(1));
mData(i,2) = str2double(t(2));
delete(instrfindall); % close the serial port
csvwrite(sFile,mData); % save the data to a CSV file
else % if the file exists, load it
mData = csvread(sFile);

  댓글 수: 3

James Hornby
James Hornby 11 Apr 2015
Hi there, firstly im brand new to MATLAB today so please excuse my being useless... I am trying to achieve a similar thing and think this code could be really helpful.
Iv got an Arduino that recieves packets from an XBee (not too important) the serial monitor recieves the packets in this form:
0 12 92 0 7D 33 A2 0 40 C1 AE 67 95 C0 1 1 0 0 8 2 6 3B 7E 0
0 12 92 0 7D 33 A2 0 40 61 1A F6 21 A6 1 1 0 0 8 2 5 2D 7E 0
0 12 92 0 7D 33 A2 0 40 61 1A F9 21 A6 1 1 0 0 8 2 7 2A 7E 0
When I copy this code directly into Matlab it seems to work, (I get a few error messages that I will work through in time) but it does create a .csv file containing 2 columns and 1000 rows, (my first two values 0 and 12 from my packets) which is brilliant, however, how would I need to alter the code in order to read the whole packet (1000x23 array) into the .csv file?
even better, the only values of the packets im actually interested in are Bytes(columns) 12, 20 and 21 as all the rest are the same and redundant. is there any way you could make a 1000x3 array just containing bytes 12,20 & 21.
All help would be greatly appreciated.
Kind Regards James
James Hornby
James Hornby 11 Apr 2015
Hi, Iv sort of managed to get it to work by copying and pasting the line:
mData(i,1) = str2double(t(1));
Replacing it with:
mData(i,1) = hex2dec(t(1));
and Iv managed to select just the 12, 20th and 21st byte of the packet.
However, the function never runs to completion and to generate my .csv file, it only manages between 20 and 70 cycles before it crashes out and produces the error message:
"Error using serial/fscanf (line 154) Unsuccessful read: Index exceeds matrix dimensions.
Error in RouterPacketIn (line 14) sSerialData = fscanf(s1); %read sensor"
Any thoughts on what is causing the crash? If its something to do with errors in the comms is there any way of just telling the code to ignoore it and carry on?
Thanks again
aqsa aqsa
aqsa aqsa 21 Sep 2016
Hi, James. i am working on a matlab code which recieves values in the form of string from arduino. And there are four values in a string i recieve. Now i have to split all four of these in a cell array. But after storing first two values i am recieving the error of Index exceeds matrix dimensions. Please guide me how u manage to read the values in an array of 1000x3.

로그인 to comment.

Chirag Gupta
Chirag Gupta 1 Aug 2014
Have you taken a look at the Serial_Monitor? Might solve your issue

  댓글 수: 2

Ritter 4 Aug 2014
Thank you for the reply. This was exactly what I needed. However, it outputs nonsense characters when I run the Arduino. I tried to fix this by changing the baud rate on the Matlab side(in the "Test & measurement Tool")to match the baud rate of the Arduino, and it still outputs these characters. Do you know how to remedy this?
harold 14 May 2018
Hey, did you solved the situation? If so, would you mind sharing the code? Because I face with a similar problem. Thx.

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.


Translated by