Weird "in an assignment, number of elements must be the same" error

1 view (last 30 days)
So, I have the below MATLAB code, which opens the Arduino on the serial port, and tries to read from it 1125 integer values, and plot them (continuously). On the Arduino side, I'm just printing to the Serial port a series of integers of type 'long' (32 bits on Arduino), separated by a newline character. I'm printing a lot of these numbers, so the loops below definitely terminate (or should terminate) before I run out of printed numbers.
arduino = serial('COM3', 'BaudRate', 115200);
fopen(arduino);
grid on;
t = linspace(1, 1125, 1125);
try
A = zeros(1125);
for i=1:100
for j=1:1125
A(j) = fscanf(arduino, '%d');
end
plot(t,A);
shg;
end
fclose(arduino);
catch err
disp(err);
fclose(arduino);
end
This works for about 4-6 iterations of the outer loop, (I see the plot appear and change 4-6 times), and then suddenly, I get this error in the middle of the (usually) 7th iteration:
'In an assignment A(I) = B, the number of elements in B and I must be the same.' This refers to the "A(j) = fscanf(arduino, '%d');" line. It happens at some random value in the inner for loop, as I found out after some printing.
What's weird is that it was working perfectly fine before. It was reading the data and plotting it fine. Then suddenly it stops and gives the error, while both sides of the assignment are the same size (fscanf will give an integer, and the A list contains integers).
When I make the following edits inside the try block:
for i=1:100
j=1;
while j<=1117
A(j:j+7) = fscanf(arduino, '%d', 32);
j=j+8;
end
plot(t,A);
shg;
end
Then the outer loop works for about 20 iterations then crashes. The result is that the plot is of lower resolution. (I'm not sure what the fscanf(A,'format',size) does, exactly, but it looks like it just took one integer of the next 32 bytes and set it to all 8 entries of A(j:j+7). Which is definitely not what's wanted.)
Can anyone tell me how to fix this?
  1 Comment
dpb
dpb on 31 Jul 2014
Edited: dpb on 31 Jul 2014
I'd guess it's a timing issue -- most of the time there's one string of characters that can be converted to a single value but once in a while there are two (or more). When that happens, since you have the LHS as a single array element, there will be a size mismatch as the error says.
I've never had access to the Arduino so don't know how its protocol works but you need to ensure there's a complete reading available and read it and if there's more characters than a single value, check for it.
ADDENDUM
One way would seem to be to use the optional SIZEA argument to fscanf
fscanf(arduino, '%d',1); % return a single reading

Sign in to comment.

Answers (0)

Categories

Find more on MATLAB Support Package for Arduino Hardware in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!