1

I am having Arduino just output a consistent set of numbers to the COM port. Matlab is reading the COM port and about 1 in 10 times it reads successfully. The other times it adds an extra character or two on the first line. Usually it's a letter with some sort of accent. Below is the code for Matlab and Arduino. What could be adding the extra characters?

Arduino Code

int output1, output2, output3, area;
void setup()
{
 Serial.begin (9600)
}
void loop() 
{
output1 = 2.0;
output2 = 2.1;
output3 = 3.7;

delay(5);
Serial.print(2.0);
Serial.print(',');
Serial.print(2.1);
Serial.print(',');
Serial.println(3.7);
}

Matlab Code

clear all 
close all
Serialport='com3';
MaxDeviation=3;
TimeInterval=0.2;
loop=120;

s = serial(Serialport);

distance1(1)=0;
time(1)=0;
count = 2;
k=1;
fopen (s);
while ~isequal(count,loop)

%%Serial data accessing 

 distance1 = fgetl(s);
 distance2= textscan(distance1,'%f %f %f','Delimiter', ',');
 distance3(count + 1) = cell2mat(distance2');

 area=(0.5*2.094*((distance3(count,1))^2 + (distance3(count,1))^2 + (distance3(count,1))^2));

count = count + 1;
end

%% Clean up the serial port
fclose(s);
delete(s);
clear s;
3
  • Welcome to SO! Nice first question, but generally remove any pleasantries and simply state the question you're hoping to have answered. Commented Feb 8, 2016 at 19:00
  • To further isolate your problem, if you print distance1 do you already see the characters in there? Commented Feb 8, 2016 at 21:04
  • I haven't tried printing it, but when I look at the variable, distance1 has the characters there. I will try printing it and see if the characters are there. I do know that they are not there in the arduino output. Commented Feb 9, 2016 at 22:41

1 Answer 1

1

Well, you usually have to discard the first line, since you don't know when you are turning the serial on.

I mean, you are printing

2.0,2.1,3.7\r\n

but you can open the port when you have just transmitted the 3, so you will receive

.7\r\n

So just put an fgetl after the fopen and you should read correctly.

Just as a note, it's always a good practice to put a starting character in the stream, so you can align at start. Now, since you are sending a new line, you can synchronize on it

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.