基于Codesys的CAN2.0B通讯,用的合信PLC,CPU自带一个CAN口,连接广成CAN盒子,进行测试;can总线在新能源行业船舶行业应用比较多,BMS,逆变器,充电机等。
变量声明:PROGRAM ST_MainVAR Can_InterFaces:CanInterFaces; candrive_29bit:CAN.CANDriver_29bit; X2: BOOL; config1: CAN.DRIVER_CONFIG; send1:CAN.CANSender; mes1: CAN.MESSAGE; singid:CAN.CANSingleIdReceiver;//通过掩码方式接收 maskreceiver:CAN.CANMaskReceiver; sid: CAN.RECEIVER_SINGLE_ID := (dwCanId := 16#30, x29BitIdValue := TRUE, x29BitIdMask := TRUE, xTransmitMask := TRUE); mask1: CAN.RECEIVER_MASK := (x29BitIdValue := TRUE, x29BitIdMask := TRUE, xTransmitMask := TRUE); sig_time: BLINK; sig_out: BOOL; byte0: ARRAY[0..7] OF byte; word0, word1: word; dword0, dword1: dword; FrameID: dword; DataAddress: word; sig_f: F_TRIG;END_VAR
主程序:sig_time(ENABLE:= TRUE , TIMELOW:=T#5MS , TIMEHIGH:=T#5MS , OUT=>sig_out );
config1.usiNetwork:=0; //网络端口config1.uiBaudrate:=1000;//波特率config1.ctMessages:=10;//长度//can配置candrive_29bit( xEnable:= TRUE , //触发位 xDone=> , xBusy=> , xError=> , xResetBusAlarm:= X2, //报警复位 DriverConfig:= config1, //can总线配置 xBusAlarm=> , eError=> );
sig_f(CLK:=sig_out , Q=> );
IF sig_f.Q THEN//帧ID自减1 IF FrameID < 1 THEN FrameID:=32766; ELSE FrameID:=FrameID-1; END_IF IF DataAddress > 32766 THEN//数据地址自加1 DataAddress:=0; ELSE DataAddress:=DataAddress+1; END_IF END_IF
//配置CAN发送,帧ID,数据,长度,标志位mes1.udiCanID:=FrameID;//发送的帧IDmes1.abyData[0]:=WORD_TO_BYTE(SHR(DataAddress,8) ); //发送的数据mes1.abyData[1]:=WORD_TO_BYTE(DataAddress);mes1.abyData[2]:=16#1A; mes1.abyData[3]:=16#2B; mes1.abyData[4]:=16#3C; mes1.abyData[5]:=16#4D; mes1.abyData[6]:=16#5E; mes1.abyData[7]:=16#6F; mes1.usiDataLength:=8;//要发送的数据长度mes1.xIs29BitMessage:=TRUE;//发送的是扩展帧,这个地方要置1 //can发送 send1( xExecute:= sig_out, //触发位 xDone=> , xBusy=> , xError=> , itfCANDriver:= candrive_29bit , //CAN配置,上面的实例--candrive_29bit Message:= mes1, //要发送的消息 eError=> );
//根据掩码接收maskreceiver( xEnable:= TRUE, xDone=> , xBusy=> , xError=> , itfCANDriver:= candrive_29bit, itfMsgProcessor:= Can_InterFaces, //接收 tTimeLimit:= T#5MS , Mask:= mask1, eError=> );
[ 此帖被clyzzc在2024-08-14 10:10重新编辑 ]