私のコードを検索して遊んだ後、私はこれをどのように動作させるかを考え出しました。 Reading raw serial data in Matlab
whileループ内の両方のデバイスにfscanfまたはfgetsを使用する代わりに、サンプリングレートが異なるためにデータの遅延の問題が発生しましたが、それぞれに対して2つの関数ファイルを作成しましたデバイスは、メインwhileループ内でコールバックを読み取り、使用して、BytesAvailableFcnステータスをチェックします。
以下は完全な例です。
----------------------- main_file.m -------------------- ---
% Create global arrays for main and function scripts visibility
global device1_array;
global device2_array;
% Create COM port variables for each device
s_device1 = serial('COM2', 'BaudRate', 19200, 'DataBits', 8, 'Parity', 'none', 'StopBits', 1, 'BytesAvailableFcnMode', 'terminator');
s_device2 = serial('COM3', 'BaudRate', 9600, 'DataBits', 8, 'Parity', 'none', 'StopBits', 1, 'BytesAvailableFcnMode', 'terminator');
% Open COM ports
fopen(s_device1);
fopen(s_device2);
% Create data figure and stop button to exit loop
fig = figure(1);
tb = uicontrol(fig, 'Style', 'togglebutton', 'String', 'Stop');
drawnow;
while(1)
% Check for button click to exit loop
drawnow;
if (get(tb, 'Value')==1); break; end
% Callbacks to check when data is ready from either device
s_device1.BytesAvailableFcn = @device1_serial_callback;
s_device2.BytesAvailableFcn = @device2_serial_callback;
% Plot variables
subplot(2, 1, 1);
plot(device1_array);
subplot(2, 1, 2);
plot(device2_array);
end
% Close COM ports
fclose(s_device1);
fclose(s_device2);
% Delete COM port variables
delete(s_device1);
delete(s_device2);
----------------------- device1_serial_callback.m -------------- ---------
function device1_serial_callback(obj, event)
global device1_array;
if (obj.BytesAvailable > 0)
device1_data = fgets(obj); % likely will need to process raw data
device1_array = [device1_array device1_data];
end
end
----------------------- device2_serial_callback.m --------- ---------------
function device2_serial_callback(obj, event)
global device2_array;
if (obj.BytesAvailable > 0)
device2_data = fgets(obj); % likely will need to process raw data
device2_array = [device2_array device2_data];
end
end