Main Content

本页翻译不是最新的。点击此处可查看最新英文版本。

MATLAB CAN 通信快速入门

以下示例说明如何使用 CAN 通道传输和接收 CAN 报文。它使用以环回配置形式连接的 MathWorks® 虚拟 CAN 通道。

创建接收通道

通过指定供应商名称、设备名称和设备通道索引,使用 canChannel 创建一个 CAN 通道以接收报文。

rxCh = canChannel("MathWorks", "Virtual 1", 2);

检查通道

使用 get 命令获取有关所有通道属性及其当前值的更多详细信息。

get(rxCh)
        ArbitrationBusSpeed: []
               DataBusSpeed: []
          ReceiveErrorCount: 0
         TransmitErrorCount: 0
       InitializationAccess: 1
           InitialTimestamp: [0×0 datetime]
                 SilentMode: 0
           TransceiverState: 'N/A'
                   BusSpeed: 500000
               NumOfSamples: []
                        SJW: []
                      TSEG1: []
                      TSEG2: []
                  BusStatus: 'N/A'
            TransceiverName: 'N/A'
                   Database: []
         MessageReceivedFcn: []
    MessageReceivedFcnCount: 1
                   UserData: []
              FilterHistory: 'Standard ID Filter: Allow All | Extended ID Filter: Allow All'
           MessagesReceived: 0
        MessagesTransmitted: 0
                    Running: 0
                     Device: 'Virtual 1'
         DeviceChannelIndex: 2
         DeviceSerialNumber: 0
               DeviceVendor: 'MathWorks'
               ProtocolMode: 'CAN'
          MessagesAvailable: 0

启动通道

使用 start 命令将通道设置为在线状态。

start(rxCh);

传输报文

示例函数 generateMsgs 使用 canMessage 创建 CAN 报文,并使用 transmit 以不同周期性速率传输它们。它会在 CAN 总线上生成流量,用于演示目的。

type generateMsgs
function generateMsgs()
% generateMsgs Creates and transmits CAN messages for demo purposes.
%
%   generateMsgs periodically transmits multiple CAN messages at various
%   periodic rates with changing message data.
%

% Copyright 2008-2016 The MathWorks, Inc.

    % Create the messages to send using the canMessage function. The 
    % identifier, an indication of standard or extended type, and the data
    % length is given for each message.
    msgTx100 = canMessage(100, false, 0);
    msgTx200 = canMessage(200, false, 2);
    msgTx400 = canMessage(400, false, 4);
    msgTx600 = canMessage(600, false, 6);
    msgTx800 = canMessage(800, false, 8); 

    % Create a CAN channel on which to transmit.
    txCh = canChannel('MathWorks', 'Virtual 1', 1);

    % Register each message on the channel at a specified periodic rate.
    transmitPeriodic(txCh, msgTx100, 'On', 0.500);
    transmitPeriodic(txCh, msgTx200, 'On', 0.250);
    transmitPeriodic(txCh, msgTx400, 'On', 0.125);
    transmitPeriodic(txCh, msgTx600, 'On', 0.050);
    transmitPeriodic(txCh, msgTx800, 'On', 0.025);
    
    % Start the CAN channel.
    start(txCh);
    
    % Run for several seconds incrementing the message data regularly.
    for ii = 1:50
        % Increment the message data bytes.
        msgTx200.Data = msgTx200.Data + 1;
        msgTx400.Data = msgTx400.Data + 1;
        msgTx600.Data = msgTx600.Data + 1;
        msgTx800.Data = msgTx800.Data + 1;
        
        % Wait for a time period.
        pause(0.100);
    end

    % Stop the CAN channel.
    stop(txCh);
end

对于该示例,运行 generateMsgs 函数以传输报文。

generateMsgs();

接收报文

generateMsgs 完成时,使用 receive 函数接收来自通道的所有可用报文。

rxMsg = receive(rxCh, Inf, "OutputFormat", "timetable");

使用 head 提取接收的报文的前几行进行预览。

head(rxMsg)
       Time        ID     Extended       Name              Data            Length      Signals       Error    Remote
    ___________    ___    ________    __________    ___________________    ______    ____________    _____    ______

    0.31722 sec    100     false      {0×0 char}    {1×0 uint8        }      0       {0×0 struct}    false    false 
    0.31723 sec    200     false      {0×0 char}    {[            0 0]}      2       {0×0 struct}    false    false 
    0.31723 sec    400     false      {0×0 char}    {[        0 0 0 0]}      4       {0×0 struct}    false    false 
    0.31723 sec    600     false      {0×0 char}    {[    0 0 0 0 0 0]}      6       {0×0 struct}    false    false 
    0.31723 sec    800     false      {0×0 char}    {[0 0 0 0 0 0 0 0]}      8       {0×0 struct}    false    false 
    0.34689 sec    800     false      {0×0 char}    {[1 1 1 1 1 1 1 1]}      8       {0×0 struct}    false    false 
    0.37728 sec    600     false      {0×0 char}    {[    1 1 1 1 1 1]}      6       {0×0 struct}    false    false 
    0.37729 sec    800     false      {0×0 char}    {[1 1 1 1 1 1 1 1]}      8       {0×0 struct}    false    false 

停止通道

使用 stop 命令将通道设置为离线状态。

stop(rxCh);

分析收到的报文

MATLAB® 为执行 CAN 报文分析提供功能强大的环境。plot 命令可以创建具有报文时间戳和标识符的散点图,以便概览某些报文何时出现在网络上。

plot(rxMsg.Time, rxMsg.ID, "x")
ylim([0 2047])
xlabel("Timestamp")
ylabel("CAN Identifier")