CAN통신 메모 1

C++/CubeMX 2021. 4. 26. 18:37

//can.h

/* USER CODE BEGIN Private defines */
extern CAN_FilterTypeDef canFilter1;//수신시 필터 설정(수신에서만 사용)
extern CAN_RxHeaderTypeDef canRxHeader;//수신받은 데이터의 헤더 정보 저장
extern CAN_TxHeaderTypeDef canTxHeader;//송신하는 데이터의 헤더 정보 저장
extern uint8_t can1Rx0Data[8];//수신 할 데이터 저장하는 변수
extern uint32_t TxMailBox;
extern uint8_t can1Tx0Data[8];//송신 할 데이터 저장하는 변수
/* USER CODE END Private defines */


//can.c

/* USER CODE BEGIN 0 */
CAN_FilterTypeDef canFilter1;//수신시 필터 설정(수신에서만 사용)
CAN_RxHeaderTypeDef canRxHeader;//수신받은 데이터의 헤더 정보 저장
CAN_TxHeaderTypeDef canTxHeader;//송신하는 데이터의 헤더 정보 저장
uint8_t can1Rx0Data[8];//수신 할 데이터 저장하는 변수
uint32_t TxMailBox;
uint8_t can1Tx0Data[8];//송신 할 데이터 저장하는 변수
/* USER CODE END 0 */

 

//main.c

/* USER CODE BEGIN 2 */
  //CAN Filter 설정
  canFilter1.FilterMaskIdHigh = 0xFF8 << 5;//FilterMaskID <<5하는 이유는 상위 레지스터에 할당되어 있기 떄문 그냥 쓰셈
  canFilter1.FilterIdHigh = 0x100 << 5;//FilterID
  canFilter1.FilterMaskIdLow = 0xFF8 << 5;
  canFilter1.FilterIdLow = 0x100 << 5;
  canFilter1.FilterMode = CAN_FILTERMODE_IDMASK;
  canFilter1.FilterScale = CAN_FILTERSCALE_16BIT;
  canFilter1.FilterFIFOAssignment = CAN_FILTER_FIFO0;
  canFilter1.FilterBank = 0;
  canFilter1.FilterActivation = ENABLE;
  
  HAL_CAN_ConfigFilter(&hcan1, &canFilter1);
  HAL_CAN_ActivateNotification(&hcan1, CAN_IT_RX_FIFO0_MSG_PENDING);//수신 인터럽트 설정
  
  HAL_CAN_Start(&hcan1);//CAN통신 시작 코드
  /* USER CODE END 2 */

//main.c
while
(1)

{

  /* USER CODE END WHILE */

   if(SW1_flag)//CAN통신 송신부 //시리얼통신 들어온 뒤로 옮길 것

   {

   SW1_flag = 0;

   canTxHeader.StdId = 0x102;

   canTxHeader.RTR = CAN_RTR_DATA;

   canTxHeader.IDE = CAN_ID_STD;

   canTxHeader.DLC = 8;

 

   for(int i = 0; i<8; i++)

   {

       can1Tx0Data[i]++;

   }

   TxMailBox = HAL_CAN_GetTxMailboxesFreeLevel(&hcan1);

   HAL_CAN_AddTxMessage(&hcan1, &canTxHeader, &can1Tx0Data[0], &TxMailBox);

}

/* USER CODE BEGIN 3 */

}

/* USER CODE END 3 */

 

참고 영상

www.youtube.com/watch?v=84IAJDuJdxc

www.youtube.com/watch?v=6vR3lX8ojDA

www.youtube.com/watch?v=T65WpTyv8Po

 

: