Mitch T February 2016

Matlab is reading extra characters from arduino serial output

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;

Answers


frarugi87 February 2016

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

Post Status

Asked in February 2016
Viewed 3,790 times
Voted 9
Answered 1 times

Search




Leave an answer