基于Codesys的CAN2.0B通訊,用的合信PLC,CPU自帶一個CAN口,連接廣成CAN盒子,進行測試;can總線在新能源行業(yè)船舶行業(yè)應用比較多,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 , //觸發(fā)位 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發(fā)送,幀ID,數據,長度,標志位mes1.udiCanID:=FrameID;//發(fā)送的幀IDmes1.abyData[0]:=WORD_TO_BYTE(SHR(DataAddress,8) ); //發(fā)送的數據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;//要發(fā)送的數據長度mes1.xIs29BitMessage:=TRUE;//發(fā)送的是擴展幀,這個地方要置1 //can發(fā)送 send1( xExecute:= sig_out, //觸發(fā)位 xDone=> , xBusy=> , xError=> , itfCANDriver:= candrive_29bit , //CAN配置,上面的實例--candrive_29bit Message:= mes1, //要發(fā)送的消息 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重新編輯 ]