一、問題描述

想透過comport來接收Event
而comport為RS232的線材傳輸
先前的comport 接收藍芽資料為連續型的
 之前的文章:Matlab com port 連線 (bluetooth)
而這次是要接收非連續型的資料

os. 想搞死人嗎???
  為了這非連續型的問題,耗了本姑娘我兩天的工作天
  網路找解決方案找很久,卻一直無法解套~
  好在在最後跨年放假前找到解決方式了
  呼~~~

原先會遇到的錯誤訊息如下:
  a =fread(s); 
  Warning: Unsuccessful read: The specified amount of data was not returned within the Timeout period. 

  a =fscanf(s);
  Warning: Unsuccessful read: A timeout occurred before the Terminator was reached.

二、方法(matlab程式)

s = serial('COM45'); %assigns the object s to serial port
set(s, 'InputBufferSize', 256); %number of bytes in inout buffer
set(s, 'FlowControl', 'hardware');
set(s, 'BaudRate', 9600);
set(s, 'Parity', 'none');
set(s, 'DataBits', 8);
set(s, 'StopBit', 1);
set(s, 'Timeout',10);

disp(get(s,'Name'));
prop(1)=(get(s,'BaudRate'));
prop(2)=(get(s,'DataBits'));
prop(3)=(get(s, 'StopBit'));
prop(4)=(get(s, 'InputBufferSize'));

disp(['Port Setup Done!!',num2str(prop)]);

fopen(s); %opens the serial port
t=1;
disp('Running');
x=0;
a=0;
while(t < 300) %Runs for 200 cycles - if you cant see the symbol, it is "less than" sign. so while (t less than 200)
  %a =fread(s); %reads the data from the serial port and stores it to the matrix a
  %a =fscanf(s);
  
  readasync(s);  <--就是這行....關鍵行.....耗了本姑娘2天的時間!!!
  if (s.BytesAvailable > 0)
   a = fread(s,s.BytesAvailable,'uint8');
  end
  a=max(a); % in this particular example, I'm plotting the maximum value of the 256B input buffer
  x =[x a];  % Merging the value to an array, this is not very computationaly effective, as the array size is dynamic.
        %Consider pre allocation the size of the array to avoid this. But beware, You might loose some important
        %data at the end!

  plot(x);
  axis auto;
  grid on;

  disp([num2str(t),'th iteration max= ',num2str(a)]);
  hold on;
  t=t+1;
  a=0; %Clear the buffer
  drawnow;
end

fclose(s); %close the serial port


呼~~~
終於。。。
  可繼續往下做事了 

文章標籤
創作者介紹
創作者 HuangJung1216 的頭像
HuangJung1216

HuangJung1216的部落格

HuangJung1216 發表在 痞客邦 留言(0) 人氣()