这个示例向您展示了如何使用CAN通道来发送和接收CAN消息。它使用在环回配置中连接的MathWorks虚拟CAN通道。
使用。创建CAN通道canChannel
通过指定供应商名称、设备名称和设备通道索引来接收消息。
rxCh = canChannel (“MathWorks”,“虚拟1”2);
使用得到
命令获取有关所有通道属性及其当前值的更详细信息。
get (rxCh)
ArbitrationBusSpeed: [] DataBusSpeed: [] ReceiveErrorCount: 0 TransmitErrorCount: 0 InitializationAccess: 1 InitialTimestamp: [0 x0 datetime] SilentMode: 0 TransceiverState:“N / A”BusSpeed: 500000 NumOfSamples: [] SJW: [] TSEG1: [] TSEG2: [] BusStatus:“N / A”TransceiverName:“N / A”数据库:[]MessageReceivedFcn: [] MessageReceivedFcnCount:1 UserData: [] FilterHistory: 'Standard ID Filter: Allow All | Extended ID Filter: Allow All' MessagesReceived: 0 messagesstranscommitted: 0 Running: 0 Device: 'Virtual 1' DeviceChannelIndex: 2 DeviceSerialNumber: 0 DeviceVendor: 'MathWorks' ProtocolMode: 'CAN' MessagesAvailable: 0 .使用实例
使用开始
命令,设置通道在线。
开始(rxCh);
函数的例子generateMsgs
使用以下命令创建CAN消息canMessage
并使用传输
以不同的周期速率。它在CAN总线上生成流量,用于演示。
类型generateMsgs
函数generateMsgs() % generateMsgs为演示目的创建并传输CAN消息。% % generateMsgs周期性地以不同的%周期率发送多个CAN消息,消息数据不断变化。使用canMessage函数创建要发送的消息。为每条消息指定了%标识符(表示标准或扩展类型)和数据%长度。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);%创建要传输的CAN通道。 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
完成后,使用收到
函数。
rxMsg = receive(rxCh, Inf,“OutputFormat”,“时间表”);
使用头
提取接收到的消息的前几行以供预览。
头(rxMsg)
ans =8×8的时间表时间ID扩展名称数据远程信号长度错误 ___________ ___ ________ __________ ___________________ ______ ____________ _____ ______ 0.30321秒100假{0 x0 char} 0 x0 uint8 {1} {0 x0 struct}假假0.30321秒200假{0 x0 char} {[0 0]} {0 x0 struct} 2假假0.30322秒400假{0 x0 char} {[0 0 0 0]} 4 {0 x0 struct}假假0.30322秒600假{0 x0 char} {[0 0 0 0 0 0]} 6 {0 x0 struct}假假0.30322秒800假{0 x0 char} {[0 0 0 0 0 0 0 0]} {0 x0 struct} 8假假0.3282秒800假{0 x0 char} {[1 1 1 1 1 1 1 1]} {0 x0 struct} 8假假0.35436秒600假{0 x0 char} {[1 1 1 1 1 1]} 6 {0 x0 struct} 800假假假0.35436秒{0x0 char} {[1 1 1 1 1 1 1]} 8 {0x0 struct} false false
使用停止
命令,使通道脱机。
停止(rxCh);
MATLAB为CAN消息的分析提供了一个强大的环境。的情节
命令可以创建带有消息时间戳和标识符的散点图,以提供某些消息何时在网络上发生的概述。
情节(rxMsg。时间,rxMsg。ID,“x”) ylim([0 2047])“时间戳”) ylabel (“标识符”)