CAN匯流排 樹德科技大學資訊工程系 吳鴻志副教授
簡介 主題:利用學習版實作CAN匯流排 單元名稱:CAN匯流排 學習時數:3小時 適用對象:資訊工程系大三學生
課程綱要 OutLine CAN匯流排原理與通訊協定介紹 CAN 驅動程式介紹 實習範例 : CAN基本傳輸 實習範例 : CAN Tx & Keypad輸入 實習範例 : CAN Rx & LCD輸出
CAN 簡介 (Controller Area Network) 德國BOSCH公司自1983年開始發展,1986年成為SAE官方標準,1993年列入ISO 11898國際標準 為汽車控制而開發 簡化佈線 提高可靠度與維護性 已廣泛應用於工業自動化與即時控制 串列控制網路,最快速度為1 Mbps 廣播型的網路,網路中的節點不分主從
CAN 網路架構
ISO/OSI Reference Model
ISO/OSI Reference Model
ISO 11898 Standards Part 1: Data link layer and physical signaling, 2003 Part 2: High-speed medium access unit, 2003 Part 3: Low-speed, fault-tolerant, medium-dependent interface, 2006 Part 4: Time-triggered communication, 2004 Part 5: High-speed medium access unit with low-power mode, 2007
SAE J1939 set of profiles J1939/11 Physical layer (250 kbit/s, twisted shielded pair) J1939/13 Off-board diagnostic connector J1939/15 Reduced physical layer (250 kbit/s, unshielded twisted pair) J1939/21 Data link layer J1939/31 Network layer J1939/71 Vehicle application layer J1939/73 Application layer diagnostics J1939/74 (Draft) Application - Configurable messaging J1939/75 Application layer - Generator sets and industrial J1939/81 Network management
ISO Standards (application layer) 11783-1~13/Isobus : Tractors and machinery for agriculture and forestry -- Serial control and communications data network (2001~2009,農林業機械) 11992-1~4 : Road vehicles -- Interchange of digital information on electrical connections between towing and towed vehicles (2003~2008,卡車、巴士) 17356-1~6 : Road vehicles -- Open interface for embedded automotive applications (2005~2006)
Application layers CANopen (http://www.can-cia.de/,CiA DS-301) CANaerospace (http://www.canaerospace.net/,空用) ISObus/ISO 11783 (http://www.isobus.net/,農林業) DeviceNet (http://www.odva.org/) NMEA 2000 (http://www.nmea.org/,船舶導航) MilCAN (http://www.milcan.org/,軍用車輛) SafetyBUS p (http://www.safetybus.de/,工廠自動化) CAN Kingdom (http://www.kvaser.se/)
汽車工業的需求 需求:安全、舒適、節能 Electronic Control Unit (ECU) 汽車維修 安全:ABS、安全氣囊、循跡控制 ... 舒適:空調、中控鎖、電動座椅、車窗、後視鏡 ... 節能:引擎控制、點火控制、感測器 ... 汽車維修 CONSULT OBD II (On Board Diagnostic II) CAN bus
CAN Bus 的應用 交通:汽車、火車、輪船、航空 製造:機器控制、工廠自動化、生產線 建築:電梯、門禁、空調 農林業:農作收割機、耕耘機 保健:醫療設備、手術室、保健器材 娛樂:燈光控制、博弈機、玩具 科學:高能物理設備、天文望遠鏡 ...
汽車電子控制裝置 1 巡航控制 2 MK60E:電子煞車系統 主動式安全系統 10 四輪煞車 被動式安全系統 8 雙向預縮式安全帶 主動式安全系統 10 四輪煞車 被動式安全系統 8 雙向預縮式安全帶 11 接近速度感測器 12 側撞感測器 13 前撞感測器 14 安全氣囊控制器 3 電子式穩定控制感測器 4 Gateway data transmitter 5 力回饋加速踏板 LIN (Local Interconnect Network) 6 車門控制單元 7 天窗控制單元 9 座椅控制單元
Car Network
船舶控制與導航
CAN 應用於農業機械控制
其他應用實例
CAN 基本規格 Transfer rate: 1 Mbps max. Max. message length: 8 bytes Carrier Sense Multiple Access/Bitwise Arbitration (CSMA/BA) Fault tolerance: 15 bits CRC + ACK Media: twisted pair
CAN bus access & arbitration CSMA/CD and AMP
Non-Destructive Bitwise Arbitration
CAN Bit Coding & Bit Staffing Bit Coding : NRZ(Non-Return-To-Zero code) does not ensure enough edges for synchronization Stuff Bits are inserted after 5 consecutive bits of the same level Stuff bits have the inverse level of the previous bit No deterministic encoding, frame length depends on transmitted data
CAN Bus Synchronization
CAN Bit Construction
Relation between Baud Rate and Bus Length
Frame 格式
Data Rate vs. Bus Length Data Rate Length 1 Mbit/s 40 m 500 kbit/s 1 km 10 kbit/s 6 km
Error detection and error confinement Frame level Cyclic Redundancy Checks (CRC) Frame check ACK error check Bit level Bit monitor Bit stuffing
CAN-H GND 波形
CAN-L GND 波形
Bosch CAN2.0b controller feature Support CAN protocol version 2.0 part A and B Bit rate up to 1M bit/s 32 Message Objects Error Message Object has its own identifier mask Programmable FIFO mode (concatenation of Message object) Maskable interrupt Disable Automatic Re-transmission mode for Time Triggered CAN application Programmable loop-back mode for self-test operation 16-bit module interface to AMBA APB bus Support wake-up function
CAN controller block diagram
CAN controller block function CAN_core (CAN 協定控制核) CAN protocol controller and TX/RX Shift Registers for parallel/serial conversion of messages Message RAM (訊息記憶體) Store Message Objects and Identifier Masks Registers (暫存器) All registers used to control and to configure the CAN controller Message Handler (狀態機) State Machine that controls the data transfer between the TX/RXShift Register of the CAN core and the Message RAM, and interrupts generation Module Interface (模組界面) Interface of AMBA APB 16 bit bus
Functional Description Software Initialization Setting the Init bit by software or hardware reset, or by Bus_Off state While Init bit is set, all message transfer to and from the CAN bus are stopped the status of CAN_TX output pin is recessive (High). The Error Management Logic (EML) counters are unchanged. Setting Init bit did not change any configuration register. To initialize the CAN controller, software has to set up the Bit Timing Register and each Message Object. If a Message Object is not required, the corresponding MsgVal bit should be cleared. Reset the Init bit (by software only) finishes the software initialization
Functional Description CAN Message Transfer Once CAN controller is initialized and Init bit is reset to zero, CAN core synchronizes itself to CAN bus, and starts the message transfer Received messages are stored in their appropriate Message Objects if they pass the Message Handler’s acceptance filtering. The whole message including all arbitation bits, DLC, and eight data bytes If the Identifier Mask is used, the arbitration bits which are masked to “don’t care” may be overwritten in the Message Object Software can read or write each message any time through the Interface Registers and the Message Handler guarantees data consistency in case of concurrent accesses.
Managing Message Objects The configuration of the Message Objects in the Message RAM will not be affected by chip reset (except CAN control registers : MsgVal, NewDat, IntPnd & TxRqst) All Message Objects must be initialized by the application software or they must be “not valid” (MsgVal=0) and the bit timing must be configured before the application software clears the Init bit. The configuration of a Message Object is done by programming Mask, Arbitration, Control and Data fields of one of the two interface registers to the desired value. By writing to the corresponding IFn Command Request Register, the IFn Message Buffer Registers are loaded into the addressd Message Object in the Message RAM While Init bit is cleared, CAN protocol controller’s state machine and Message Handler state machine control the internal data flow of CAN controller Received messages that pass the acceptance filtering are stored into the Message RAM messages with pending transmission request are loaded into the CAN_Core Shift Register and are transmitted through the CAN bus The application software reads received messages and update messages to be transmitted through the IFn Interface Registers. Depending on the configuration, application software is interrupted on certain CAN message and CAN error events
Message Handler State Machine The Message Handler controls the data transfer CAN_Core TX/RX Register, Message RAM, and IFn Registers The Message Handler FSM controls the following functions Data Transfer from IFn Registers to the Message RAM Data Transfer from Message RAM to the IFn Registers Data Transfer from Shift Register to the Message RAM Data Transfer from Message RAM to Shift Register Data Transfer from Shift Register to the Acceptance Filtering unit Scanning of Message RAM for a matching Message Object Handling of TxRqst flags Handling of interrupts
Data Transfer between IFn Register and Message
CAN Register Map for each bit function
CAN Register Map for each bit function
範例1: CAN基本傳輸實驗 E:\NuMicro Family MCU\BSP Library\NUC100SeriesBSP_CMSIS\NUC100SeriesBSP_CMSIS_v1.05.003\NuvotonPlatform_Keil\Sample\NUC1xx-LB_002\ Smpl_CAN
學習板上週邊的腳位使用表
GPB12, GPB13的作用
Smpl_CAN.c int main (void) // DrvGPIO_Open(E_GPD,14,E_IO_OUTPUT); // LCD backlight { // DrvGPIO_ClrBit(E_GPD,14); int32_t CAN_speed = 1000; // Kbps DrvGPIO_Open(E_GPB,12,E_IO_OUTPUT); int32_t i32Err =0; // CAN Transceiver setting STR_UART_T param; DrvGPIO_ClrBit(E_GPB,12);//控制CAN模式,高速 UNLOCKREG(); DrvSYS_SetOscCtrl(E_SYS_XTL12M,1); /* Select CAN Multi-Function */ DrvSYS_SetOscCtrl(E_SYS_OSC22M,1); DrvGPIO_InitFunction(E_FUNC_CAN0); DrvSYS_Delay(20000); DrvCAN_Init(); /* Delay for Xtal stable */ i32Err = DrvCAN_Open(CAN_speed); // set CAN speed while(!SYSCLK->CLKSTATUS.XTL12M_STB); while(!SYSCLK->CLKSTATUS.OSC22M_STB); if(i32Err<0) printf("Set CAN bit rate is fail\n"); DrvSYS_SelectHCLKSource(0);//0: External 12M clock sprintf(TEXT0+5,"%d Kbps", CAN_speed); print_lcd(0,TEXT0); /* Init GPIO and configure UART0 */ SetMaskFilter(); // set receiving message DrvGPIO_InitFunction(E_FUNC_UART0); param.u32BaudRate = 115200; param.u8cDataBits = DRVUART_DATABITS_8; sprintf(TEXT3,"SetMaskFilter"); print_lcd(3,TEXT3); param.u8cStopBits = DRVUART_STOPBITS_1; while(1) { param.u8cParity = DRVUART_PARITY_NONE; TestMaskFilter();// set sending message sprintf(TEXT3,"TestMaskFilter"); param.u8cRxTriggerLevel = DRVUART_FIFO_1BYTES; print_lcd(3,TEXT3); param.u8TimeOut = 0; } DrvUART_Open(UART_PORT0, ¶m); // DrvCAN_Close(); Initial_panel(); clr_all_panel();
Smpl_CAN.c // TX send 11-bit message // RX set Mask Filter void TestMaskFilter() void SetMaskFilter() { int32_t i32id=0; STR_CANMASK_T MaskMsg; STR_CANMSG_T tMsg; DrvCAN_EnableInt(CAN_CON_IE);//CAN_CON_IE : Module Interrupt Enable while(1) DrvCAN_InstallCallback(CALLBACK_MSG, (CAN_CALLBACK)CAN_CallbackFn); /* Send a 11-bits message */ tMsg.FrameType= DATA_FRAME; /* Set b'0' means don't care*/ tMsg.IdType = CAN_STD_ID; /* Set Messge Object No.0 mask ID */ tMsg.Id = 0x600 + i32id; MaskMsg.u8Xtd = 1; tMsg.DLC = 5;//DLC是數據傳輸長度 MaskMsg.u8Dir = 1; tMsg.Data[0] = 'N'; MaskMsg.u8IdType = 0; /* 1:EXT (29bits)or 0:STD (11bits)*/ tMsg.Data[1] = 'U'; tMsg.Data[2] = 'C'; MaskMsg.u32Id = 0x600;//遮罩方式 tMsg.Data[3] = ' '; DrvCAN_SetMsgObjMask(MSG(0),&MaskMsg); tMsg.Data[4] = 0x30+i32id; DrvCAN_SetRxMsgObj(MSG(0), CAN_STD_ID, 0x7FF , TRUE); if(DrvCAN_SetTxMsgObj(MSG(1),&tMsg) < 0) //printf("u32Id=0x600, If there is a message-ID 0x600~0x61F,\n 0x600~0x61F can pass acceptance filter.\n"); /* Call DrvCAN_SetTxMsgObj() only Confiugre Msg RAM */ printf("Set Tx Msg Object failed\n"); printf("u32Id=0x607, If there is a message-ID 0x600~0x61F,\n ONLY 0x607/0x60F/0x61F can pass acceptance filter.\n"); return; } //printf("u32Id=0x610, If there is a message-ID 0x600~0x61F,\n 0x610~0x61F can pass acceptance filter.\n"); DrvCAN_SetTxRqst(MSG(1)); i32id++; if(i32id>=0x20) break; DrvSYS_Delay(100000); printf("Waiting Message\n"); printf("Transfer Done\n");
Smpl_CAN.c /*--------------------*/ /* Callback function */ /*------------------*/ /* Test Function */ STR_CANMSG_T rrMsg; void CAN_ShowMsg(STR_CANMSG_T* Msg) void CAN_CallbackFn(uint32_t u32IIDR) { uint8_t i; if(u32IIDR==1) sprintf(TEXT1+6,"%x", Msg->Id); print_lcd(1,TEXT1); printf("Msg-0 INT and Callback\n"); //DLC是數據傳輸長度 DrvCAN_ReadMsgObj(0,TRUE,&rrMsg); for(i=0;i<Msg->DLC;i++) CAN_ShowMsg(&rrMsg); sprintf(TEXT2+6+i,"%c", } Msg->Data[i]); if(u32IIDR==5+1) print_lcd(2,TEXT2); printf("Msg-5 INT and Callback \n"); DrvCAN_ReadMsgObj(5,TRUE,&rrMsg); if(u32IIDR==31+1) printf("Msg-31 INT and Callback \n"); DrvCAN_ReadMsgObj(31,TRUE,&rrMsg);
遮罩方式 遮罩設為u32Id=0x600 若收到的ID是0x600~0x61F, /* Set b'0' means don't care*/ /* Set Messge Object No.0 mask ID */ MaskMsg.u8Xtd = 1; MaskMsg.u8Dir = 1; MaskMsg.u8IdType = 0; /* 1:EXT (29bits)or 0:STD (11bits)*/ MaskMsg.u32Id = 0x600;//遮罩方式 遮罩設為u32Id=0x600 若收到的ID是0x600~0x61F, 則 CAN_CallbackFn函數只執行 0x600~0x61F 遮罩設為u32Id=0x607 則 CAN_CallbackFn函數只執行 0x607、0x60F、0x61F 遮罩設為u32Id=0x610 則 CAN_CallbackFn函數只執行 0x610~0x61F
範例2: CAN與Timer實驗 E:\NuMicro Family MCU\BSP Library\NUC100SeriesBSP_CMSIS\NUC100SeriesBSP_CMSIS_v1.05.003\NuvotonPlatform_Keil\Sample\NUC1xx-LB_002\ Smpl_CAN_Timer
範例3: CAN與Keypad實驗 E:\NuMicro Family MCU\BSP Library\NUC100SeriesBSP_CMSIS\NUC100SeriesBSP_CMSIS_v1.05.003\NuvotonPlatform_Keil\Sample\NUC1xx-LB_002\ Smpl_CAN_Keypad
範例4: CAN與ADC實驗 E:\NuMicro Family MCU\BSP Library\NUC100SeriesBSP_CMSIS\NUC100SeriesBSP_CMSIS_v1.05.003\NuvotonPlatform_Keil\Sample\NUC1xx-LB_002\ Smpl_CAN_ADC7
作業14 修改作業13,經由CAN BUS傳送封包到手機顯示。 CAN BUS