2016-09-28 45 views
0

我有两个商业设备都通过USB连接到我的PC作为虚拟COM端口。每个设备都以设定的速率传输数据(我未定义)。我无法发送“打印”命令并接收数据,我只能在它进来时检索它。连续读取同一脚本中的两个虚拟COM端口

我能够单独访问和使用每个设备的数据,但我想知道两个如果两个采样率不同(1 Hz与2 Hz),可以处理设备吗?

是否有基于中断的方法,我可以使用它来等待每个端口接收新值并在它们进来时抓住它,而不是将所有内容放在while循环中并不断检查?

回答

0

经过一番搜索和玩弄我的代码后,我想出了如何让这个工作。非常感谢这个线程指向我在正确的方向:Reading raw serial data in Matlab

而不是使用fscanf或fgets为while循环内的两个设备,由于不同的采样率导致数据滞后问题,我创建了两个函数文件为每个设备读取并在主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