

fclose('all');

clear all
close all
canch1 = canChannel('PEAK-System', 'PCAN_USBBUS1');
configBusSpeed(canch1, 125000);

start(canch1)




function [srcID, dataID, seq_num] = DecodeCanID(rxMsg)
%This function decodes the CAN ID into various fields.
%
%Input: CAN message as returned by "recieve".  Relevant fields for this
%function are rxMsg.ID and rxMsg.Extended in some cases
%
%Outputs:  SrcID = id of CAN device that generated the message
%          DataID = id of data field
%          Sequence number.

SEQ_WIDTH = 9;  %Least significant bits
ID_WIDTH = 5;   %Next significant bits
SRC_WIDTH = 4;  %Next signfiicant bits

SEQ_MASK = 2^SEQ_WIDTH-1;
ID_MASK = 2^ID_WIDTH-1;
SRC_MASK = 2^SRC_WIDTH-1;

N = length(rxMsg);
seq_num = NaN(1,N);
dataID = NaN(1,N);
srcID = NaN(1,N);
for i = 1:N
  seq_num(i) = bitand(rxMsg(i).ID,SEQ_MASK);
  dataID(i) = bitand(bitshift(rxMsg(i).ID,-SEQ_WIDTH),ID_MASK);
  srcID(i) = bitand(bitshift(rxMsg(i).ID,-(SEQ_WIDTH+ID_WIDTH)),SRC_MASK);
end

end

