在 CAN 通信中使用报文接收回调函数
此示例说明如何使用回调函数来处理从 CAN 通道接收的报文。它使用以环回配置形式连接的 MathWorks® 虚拟 CAN 通道。此示例说明 CAN 网络的工作流,但所展示的概念也适用于 CAN FD 网络。
创建接收通道
通过指定供应商名称、设备名称和设备通道索引,使用 canChannel 创建一个 CAN 通道以接收报文。
rxCh = canChannel("MathWorks", "Virtual 1", 2)
rxCh =
Channel with properties:
Device Information
DeviceVendor: 'MathWorks'
Device: 'Virtual 1'
DeviceChannelIndex: 2
DeviceSerialNumber: 0
ProtocolMode: 'CAN'
Status Information
Running: 0
MessagesAvailable: 0
MessagesReceived: 0
MessagesTransmitted: 0
InitializationAccess: 1
InitialTimestamp: [0×0 datetime]
FilterHistory: 'Standard ID Filter: Allow All | Extended ID Filter: Allow All'
Channel Information
BusStatus: 'N/A'
SilentMode: 0
TransceiverName: 'N/A'
TransceiverState: 'N/A'
ReceiveErrorCount: 0
TransmitErrorCount: 0
BusSpeed: 500000
SJW: []
TSEG1: []
TSEG2: []
NumOfSamples: []
Other Information
Database: []
UserData: []
配置回调函数
将回调函数设置为通道上可用报文达到所需数量时运行。
rxCh.MessageReceivedFcn = @receivingFcn;
配置接收报文计数
指定触发回调函数所需的通道报文数量。
rxCh.MessageReceivedFcnCount = 30;
实现回调函数
示例回调函数接收来自通道的所有可用报文,并在每次执行时绘制 CAN 标识符对时间戳的图。
type receivingFcnfunction receivingFcn(rxCh)
% RECEIVINGFCN A CAN channel message receive callback function.
%
% This is a callback function used to receive CAN message. It receives
% messages from the channel RXCH and plots the result.
%
% Copyright 2009-2016 The MathWorks, Inc.
% Receive all available messages.
rxMsg = receive(rxCh, Inf, 'OutputFormat', 'timetable');
% Plot the signal values against their message timestamps.
plot(rxMsg.Time, rxMsg.ID, 'x');
ylim([0 2047])
xlabel('Timestamp');
ylabel('CAN Identifier');
hold all;
end
启动通道
使用 start 命令将通道设置为在线状态。
start(rxCh);
执行回调函数
函数 generateMsgs 创建 CAN 报文并以不同周期性速率传输它们,从而在 CAN 总线上产生流量。在传输报文时,每次达到属性 MessageReceivedFcnCount 指定的阈值时,回调函数就会执行。
generateMsgs();
检查剩余报文
显示通道的 MessagesAvailable 属性以查看其余报文的数量。由于可用报文计数低于指定的阈值,因此需要更多报文才能再次触发回调。
rxCh.MessagesAvailable
ans = 11
停止通道
使用 stop 命令将通道设置为离线状态。
stop(rxCh);