CAN 设备通讯实验代码+HAL 与原生库分别实现

这篇具有很好参考价值的文章主要介绍了CAN 设备通讯实验代码+HAL 与原生库分别实现。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

实验准备:
两块带有CAN 收发器的STM32 MCU板子
csdn,单片机,stm32,嵌入式硬件,CAN,汽车电子

1.HAL 库实现部分

pin 设置,依据datasheet 和原理图
csdn,单片机,stm32,嵌入式硬件,CAN,汽车电子
csdn,单片机,stm32,嵌入式硬件,CAN,汽车电子

时钟设置
csdn,单片机,stm32,嵌入式硬件,CAN,汽车电子
csdn,单片机,stm32,嵌入式硬件,CAN,汽车电子
csdn,单片机,stm32,嵌入式硬件,CAN,汽车电子

工程设置
csdn,单片机,stm32,嵌入式硬件,CAN,汽车电子
csdn,单片机,stm32,嵌入式硬件,CAN,汽车电子
csdn,单片机,stm32,嵌入式硬件,CAN,汽车电子

1) main.c文章来源地址https://www.toymoban.com/news/detail-618900.html

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "can.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */


/* Private variables ---------------------------------------------------------*/


void CAN1_Send_Test();
/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_CAN_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
		
    /* USER CODE BEGIN 3 */
		
		CAN1_Send_Test();
		HAL_Delay(3000);
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */



  1. gpio.c
/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    gpio.c
  * @brief   This file provides code for the configuration
  *          of all used GPIO pins.
  ******************************************************************************
  * @attention
  *     
  * Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "gpio.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/*----------------------------------------------------------------------------*/
/* Configure GPIO                                                             */
/*----------------------------------------------------------------------------*/
/* USER CODE BEGIN 1 */

/* USER CODE END 1 */

/** Configure pins as
        * Analog
        * Input
        * Output
        * EVENT_OUT
        * EXTI
*/
void MX_GPIO_Init(void)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);

  /*Configure GPIO pin : PtPin */
  GPIO_InitStruct.Pin = LED_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(LED_GPIO_Port, &GPIO_InitStruct);
}

/* USER CODE BEGIN 2 */

/* USER CODE END 2 */

  1. can.c
/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    can.c
  * @brief   This file provides code for the configuration
  *          of the CAN instances.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "can.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

CAN_HandleTypeDef hcan;

void ledOnGetSignal() {
	HAL_GPIO_TogglePin(GPIOC, LED_Pin);
	HAL_Delay(1000);
//	HAL_GPIO_TogglePin(GPIOC, LED_Pin);
//	//HAL_GPIO_WritePin(GPIOC, LED_Pin, GPIO_PIN_RESET);
//	HAL_Delay(1000);
}
void ledOnGetSignal2() {
	HAL_GPIO_WritePin(GPIOC, LED_Pin, GPIO_PIN_RESET);
//	HAL_GPIO_TogglePin(GPIOC, LED_Pin);
//	HAL_Delay(500);
//	HAL_GPIO_TogglePin(GPIOC, LED_Pin);
//	//HAL_GPIO_WritePin(GPIOC, LED_Pin, GPIO_PIN_RESET);
//	HAL_Delay(500);
}
/* USER CODE END Includes */
void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan)
{  
	extern int g;
   CAN_RxHeaderTypeDef  RxMessage;
   uint8_t Data[2];
 //  extern uint16_t feedback;
	
   RxMessage.DLC = 2;
   RxMessage.StdId = 0x00;
	 RxMessage.ExtId = 0x0000;
   RxMessage.IDE=CAN_ID_EXT;
   RxMessage.RTR=CAN_RTR_DATA;
	 if (HAL_CAN_GetState(hcan)!= RESET)
	 {
			HAL_CAN_GetRxMessage(hcan, CAN_RX_FIFO0, &RxMessage, Data);
		//	feedback=Data[2]<<8 |Data[3];    			
		 
		 if (Data[0] == 0x99) {
				ledOnGetSignal();
		 }
		 
		 		if (Data[0] == 0x99 ) {
				ledOnGetSignal2();
		 }
   }
}

/* CAN init function */
void MX_CAN_Init(void)
{

  /* USER CODE BEGIN CAN_Init 0 */

  /* USER CODE END CAN_Init 0 */

  /* USER CODE BEGIN CAN_Init 1 */

  /* USER CODE END CAN_Init 1 */
  hcan.Instance = CAN1;
  hcan.Init.Prescaler = 60;
  hcan.Init.Mode = CAN_MODE_NORMAL;
  hcan.Init.SyncJumpWidth = CAN_SJW_1TQ;
  hcan.Init.TimeSeg1 = CAN_BS1_3TQ;
  hcan.Init.TimeSeg2 = CAN_BS2_2TQ;
  hcan.Init.TimeTriggeredMode = ENABLE;
  hcan.Init.AutoBusOff = DISABLE;
  hcan.Init.AutoWakeUp = DISABLE;
  hcan.Init.AutoRetransmission = DISABLE;
  hcan.Init.ReceiveFifoLocked = DISABLE;
  hcan.Init.TransmitFifoPriority = ENABLE;
  if (HAL_CAN_Init(&hcan) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN CAN_Init 2 */
	CAN_FilterTypeDef sFilterConfig;
 
  sFilterConfig.FilterBank = 0;   //chenal 0
  sFilterConfig.FilterMode = CAN_FILTERMODE_IDMASK;   //????????
  sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT;  //????????32?
  sFilterConfig.FilterIdHigh = 0x0000;  //??????   
  sFilterConfig.FilterIdLow = 0x0000;   //??????   
  //MASK bit 0 means don't care,bit 0 means match 
  sFilterConfig.FilterMaskIdHigh = 0x0000;   //?????  //?????????????,???????????????? 
  sFilterConfig.FilterMaskIdLow = 0x0000;    //?????                                 
  sFilterConfig.FilterFIFOAssignment = CAN_FILTER_FIFO0; //FIFO0????FIFO1????????,?????????????FIFO0?
  sFilterConfig.FilterActivation = CAN_FILTER_ENABLE;   //enable filter
  sFilterConfig.SlaveStartFilterBank = 0;    //???can????????,????CAN??,????????
  HAL_CAN_ConfigFilter(&hcan, &sFilterConfig);
	HAL_CAN_ActivateNotification(&hcan, CAN_IT_RX_FIFO0_MSG_PENDING);
	
  /* USER CODE END CAN_Init 2 */

}

void HAL_CAN_MspInit(CAN_HandleTypeDef* canHandle)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(canHandle->Instance==CAN1)
  {
  /* USER CODE BEGIN CAN1_MspInit 0 */

  /* USER CODE END CAN1_MspInit 0 */
    /* CAN1 clock enable */
    __HAL_RCC_CAN1_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**CAN GPIO Configuration
    PA11     ------> CAN_RX
    PA12     ------> CAN_TX
    */
    GPIO_InitStruct.Pin = GPIO_PIN_11;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_12;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* CAN1 interrupt Init */
    HAL_NVIC_SetPriority(USB_LP_CAN1_RX0_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn);
  /* USER CODE BEGIN CAN1_MspInit 1 */

  /* USER CODE END CAN1_MspInit 1 */
  }
}

void HAL_CAN_MspDeInit(CAN_HandleTypeDef* canHandle)
{

  if(canHandle->Instance==CAN1)
  {
  /* USER CODE BEGIN CAN1_MspDeInit 0 */

  /* USER CODE END CAN1_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_CAN1_CLK_DISABLE();

    /**CAN GPIO Configuration
    PA11     ------> CAN_RX
    PA12     ------> CAN_TX
    */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_11|GPIO_PIN_12);

    /* CAN1 interrupt Deinit */
    HAL_NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn);
  /* USER CODE BEGIN CAN1_MspDeInit 1 */

  /* USER CODE END CAN1_MspDeInit 1 */
  }
}

/* USER CODE BEGIN 1 */

/* USER CODE END 1 */

  1. ST 老版本库
  1. main.c
/******************** ********************
 * ÎļþÃû  £ºmain.c
 * ÃèÊö    £º¸øÏàͬÁ½¸öMINI°åÏÂÔش˳ÌÐòºó£¬°´ÏÂÒ»¸ö°å×ÓÉϵİ´¼ü£¬¿ÉÒÔµãÁÁÁíÒ»¸ö°å×Ó
 *           É϶ÔÓ¦µÄLED¡£Á½¸ö°å×Ó²»·ÖÖ÷´Ó¡£     receiv site       
 * ʵÑéƽ̨£ºMINI STM32¿ª·¢°å »ùÓÚSTM32F103VET6
 * ¿â°æ±¾  £ºST3.0.0   																										  
*********************************************************/
#include "stm32f10x.h"
#include "can.h"
#include "led.h"



void Delay(vu32 nCount);

/*°´¼ü¹Ü½Å³õʼ»¯*/
void KeyInit(void)
{
        GPIO_InitTypeDef GPIO_InitStructure;

        RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);//ʹÄÜÍâÉèʱÖÓ
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);//ʹÄÜÍâÉèʱÖÓ

        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_15 ;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz; //×î¸ßÊä³öËÙÂÊ10MHz
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;//ÉÏÀ­ÊäÈë
        GPIO_Init(GPIOB, &GPIO_InitStructure);

        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz; //×î¸ßÊä³öËÙÂÊ10MHz
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //ÉÏÀ­ÊäÈë
        GPIO_Init(GPIOA, &GPIO_InitStructure);
}

void lightOn(void)
{
 
		LED1( ON );			  // ÁÁ   D3
		Delay(0x200000);
		LED1( OFF );		  // Ãð

		LED2( ON );   //D2
		Delay(0x200000);
		LED2( OFF );

		LED3( ON );   //D2
		Delay(0x200000);
		LED3( OFF );      
  
}
	
/*¼ì²âÊÇ·ñÓа´¼ü°´ÏÂ*/
void  GetKey(void)
{
        if(Bit_RESET == GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_8))
        {
                Delay(1000000);//È¥¶¶¶¯
                if(Bit_RESET == GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_8))
                {
                        while(Bit_RESET == GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_8)){ ; } //µÈ´ý°´¼üÊÍ·Å
                        can_tx(0X11,0X33); 
												lightOn();
                }
        }

        if(Bit_RESET == GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_15))
        {
                Delay(1000000);//È¥¶¶¶¯//È¥¶¶¶¯
                if(Bit_RESET == GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_15))
                {
                        while(Bit_RESET == GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_15)){ ; }//µÈ´ý°´¼üÊÍ·Å                        
                        can_tx(0X55,0X77); 
												lightOn();
                }
        }

        if(Bit_RESET == GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1))
        {
                 Delay(1000000);//È¥¶¶¶¯//È¥¶¶¶¯
                if(Bit_RESET == GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1))
                {
                        while(Bit_RESET == GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1)){ ; }//µÈ´ý°´¼üÊÍ·Å                        
                        can_tx(0X99,0Xbb); 	
												lightOn();
                }
        }       
}



int main(void)
{   
	SystemInit(); //ÉèÖÃϵͳʱÖÓΪ72M
	KeyInit();	  //°´¼ü¹Ü½Å³õʼ»¯
	LED_GPIO_Config();//LED¹Ü½Å³õʼ»¯
	CAN_GPIO_Config();//CAN¹Ü½Å³õʼ» 1¯
	CAN_NVIC_Configuration(); //CANÖжϳõʼ»¯   
	CAN_INIT();//CA³õʼ»¯NÄ£¿é	
 	while(1)
    {
	   GetKey();	//¼ì²âÊÇ·ñÓа´¼ü°´ÏÂ
	   
    }
}

  1. led.c
/****************************************
 * ÎļþÃû  £ºled.c
 * ÃèÊö    £ºled Ó¦Óú¯Êý¿â
 *          
 * ʵÑéƽ̨£ºMINI STM32¿ª·¢°å »ùÓÚSTM32F103VET6
 * Ó²¼þÁ¬½Ó£º-----------------
 *          |   PB14 - LED1   |
 *          |   PB12 - LED2   |
 *          |   PB13 - LED3   |
 *           ----------------- 
 * ¿â°æ±¾  £ºST3.0.0  																										  
*********************************************************/
#include "led.h"


 /***************  ÅäÖÃLEDÓõ½µÄI/O¿Ú *******************/
void LED_GPIO_Config(void)	
{
  GPIO_InitTypeDef GPIO_InitStructure;
  RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOB, ENABLE); // ʹÄÜPB¶Ë¿ÚʱÖÓ  
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14;	
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;       
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOB, &GPIO_InitStructure);  //³õʼ»¯PB¶Ë¿Ú
  GPIO_SetBits(GPIOB, GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14);	 // ¹Ø±ÕËùÓÐLED
}




  1. can.c
/****************************************
 * ÎļþÃû  £ºcan.c
 * ÃèÊö    £ºCAN²âÊÔÓ¦Óú¯Êý¿â¡£         
 * ʵÑéƽ̨£ºMINI STM32¿ª·¢°å »ùÓÚSTM32F103VET6
 * Ó²¼þÁ¬½Ó£º-----------------
 *          | 				  |
            |  PB8-CAN-RX     |
 *          |  PB9-CAN-TX     |
 *          |                 |
 *           -----------------
 * ¿â°æ±¾  £ºST3.0.0  																										  
*********************************************************/
#include "can.h"
#include "led.h"
#include "stdio.h"

typedef enum {FAILED = 0, PASSED = !FAILED} TestStatus;

/* ÔÚÖжϴ¦Àíº¯ÊýÖзµ»Ø */
__IO uint32_t ret = 0;

volatile TestStatus TestRx;	

/*CAN RX0 ÖжÏÓÅÏȼ¶ÅäÖà  */
 void CAN_NVIC_Configuration(void)
{
    NVIC_InitTypeDef NVIC_InitStructure;

  	/* Configure the NVIC Preemption Priority Bits */  
  	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);

	#ifdef  VECT_TAB_RAM  
	  /* Set the Vector Table base location at 0x20000000 */ 
	  NVIC_SetVectorTable(NVIC_VectTab_RAM, 0x0); 
	#else  /* VECT_TAB_FLASH  */
	  /* Set the Vector Table base location at 0x08000000 */ 
	  NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x0);   
	#endif

	/* enabling interrupt */
  	NVIC_InitStructure.NVIC_IRQChannel=USB_LP_CAN1_RX0_IRQn;;
  	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  	NVIC_Init(&NVIC_InitStructure);
}

/*CAN GPIO ºÍʱÖÓÅäÖà */
 void CAN_GPIO_Config(void)
{
  GPIO_InitTypeDef GPIO_InitStructure; 
  /* ¸´Óù¦ÄܺÍGPIOB¶Ë¿ÚʱÖÓʹÄÜ*/	 
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO | RCC_APB2Periph_GPIOB, ENABLE);	                        											 

  /* CAN1 Ä£¿éʱÖÓʹÄÜ */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN1, ENABLE); 

  /* Configure CAN pin: RX */	 // PB8
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;	 // ÉÏÀ­ÊäÈë
  GPIO_Init(GPIOB, &GPIO_InitStructure);
  
  /* Configure CAN pin: TX */   // PB9
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; // ¸´ÓÃÍÆÍìÊä³ö
  GPIO_Init(GPIOB, &GPIO_InitStructure);
  
	//#define GPIO_Remap_CAN    GPIO_Remap1_CAN1 ±¾ÊµÑéûÓÐÓõ½ÖØÓ³ÉäI/O
  GPIO_PinRemapConfig(GPIO_Remap1_CAN1, ENABLE);

  
}

/*	CAN³õʼ»¯ */
 void CAN_INIT(void)
{
  CAN_InitTypeDef        CAN_InitStructure;
  CAN_FilterInitTypeDef  CAN_FilterInitStructure;
//  CanTxMsg TxMessage;  

  /* CAN register init */
  CAN_DeInit(CAN1);	//½«ÍâÉèCANµÄÈ«²¿¼Ä´æÆ÷ÖØÉèΪȱʡֵ
  CAN_StructInit(&CAN_InitStructure);//°ÑCAN_InitStructÖеÄÿһ¸ö²ÎÊý°´È±Ê¡ÖµÌîÈë

  /* CAN cell init */
  CAN_InitStructure.CAN_TTCM=DISABLE;//ûÓÐʹÄÜʱ¼ä´¥·¢Ä£Ê½
  CAN_InitStructure.CAN_ABOM=DISABLE;//ûÓÐʹÄÜ×Ô¶¯ÀëÏß¹ÜÀí
  CAN_InitStructure.CAN_AWUM=DISABLE;//ûÓÐʹÄÜ×Ô¶¯»½ÐÑģʽ
  CAN_InitStructure.CAN_NART=DISABLE;//ûÓÐʹÄÜ·Ç×Ô¶¯ÖØ´«Ä£Ê½
  CAN_InitStructure.CAN_RFLM=DISABLE;//ûÓÐʹÄܽÓÊÕFIFOËø¶¨Ä£Ê½
  CAN_InitStructure.CAN_TXFP=DISABLE;//ûÓÐʹÄÜ·¢ËÍFIFOÓÅÏȼ¶
  CAN_InitStructure.CAN_Mode=CAN_Mode_Normal;//CANÉèÖÃΪÕý³£Ä£Ê½
  CAN_InitStructure.CAN_SJW=CAN_SJW_1tq; //ÖØÐÂͬ²½ÌøÔ¾¿í¶È1¸öʱ¼äµ¥Î»
  CAN_InitStructure.CAN_BS1=CAN_BS1_3tq; //ʱ¼ä¶Î1Ϊ3¸öʱ¼äµ¥Î»
  CAN_InitStructure.CAN_BS2=CAN_BS2_2tq; //ʱ¼ä¶Î2Ϊ2¸öʱ¼äµ¥Î»
  CAN_InitStructure.CAN_Prescaler=60;  //ʱ¼äµ¥Î»³¤¶ÈΪ60	
  CAN_Init(CAN1,&CAN_InitStructure);
                                      //²¨ÌØÂÊΪ£º72M/2/60(1+3+2)=0.1 ¼´100K

  /* CAN filter init */
  CAN_FilterInitStructure.CAN_FilterNumber=1;//Ö¸¶¨¹ýÂËÆ÷Ϊ1
  CAN_FilterInitStructure.CAN_FilterMode=CAN_FilterMode_IdMask;//Ö¸¶¨¹ýÂËÆ÷Ϊ±êʶ·ûÆÁ±Îλģʽ
  CAN_FilterInitStructure.CAN_FilterScale=CAN_FilterScale_32bit;//¹ýÂËÆ÷λ¿íΪ32λ
  CAN_FilterInitStructure.CAN_FilterIdHigh=0x0000;// ¹ýÂËÆ÷±êʶ·ûµÄ¸ß16λֵ
  CAN_FilterInitStructure.CAN_FilterIdLow=0x0000;//	 ¹ýÂËÆ÷±êʶ·ûµÄµÍ16λֵ
  CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0x0000;//¹ýÂËÆ÷ÆÁ±Î±êʶ·ûµÄ¸ß16λֵ
  CAN_FilterInitStructure.CAN_FilterMaskIdLow=0x0000;//	¹ýÂËÆ÷ÆÁ±Î±êʶ·ûµÄµÍ16λֵ
  CAN_FilterInitStructure.CAN_FilterFIFOAssignment=CAN_FIFO0;// É趨ÁËÖ¸Ïò¹ýÂËÆ÷µÄFIFOΪ0
  CAN_FilterInitStructure.CAN_FilterActivation=ENABLE;// ʹÄܹýÂËÆ÷
  CAN_FilterInit(&CAN_FilterInitStructure);//	°´ÉÏÃæµÄ²ÎÊý³õʼ»¯¹ýÂËÆ÷

  /* CAN FIFO0 message pending interrupt enable */ 
 CAN_ITConfig(CAN1,CAN_IT_FMP0, ENABLE); //ʹÄÜFIFO0ÏûÏ¢¹ÒºÅÖжÏ
 
 }  
/* ·¢ËÍÁ½¸ö×Ö½ÚµÄÊý¾Ý*/
void can_tx(u8 Data1,u8 Data2)
{ 
  CanTxMsg TxMessage;  

  TxMessage.StdId=0x00;	//±ê×¼±êʶ·ûΪ0x00
  TxMessage.ExtId=0x0000; //À©Õ¹±êʶ·û0x0000
  TxMessage.IDE=CAN_ID_EXT;//ʹÓñê×¼±êʶ·û
  TxMessage.RTR=CAN_RTR_DATA;//ΪÊý¾ÝÖ¡
  TxMessage.DLC=2;	//	ÏûÏ¢µÄÊý¾Ý³¤¶ÈΪ2¸ö×Ö½Ú
  TxMessage.Data[0]=Data1; //µÚÒ»¸ö×Ö½ÚÊý¾Ý
  TxMessage.Data[1]=Data2; //µÚ¶þ¸ö×Ö½ÚÊý¾Ý 
  CAN_Transmit(CAN1,&TxMessage); //·¢ËÍÊý¾Ý
  
}

void Delay(vu32 nCount)
{
  for(; nCount != 0; nCount--);
}

/* USBÖжϺÍCAN½ÓÊÕÖжϷþÎñ³ÌÐò£¬USB¸úCAN¹«ÓÃI/O£¬ÕâÀïÖ»Óõ½CANµÄÖжϡ£ */
void USB_LP_CAN1_RX0_IRQHandler(void)
{
  
  CanRxMsg RxMessage;

  RxMessage.StdId=0x00;
  RxMessage.ExtId=0x00;
  RxMessage.IDE=0;
  RxMessage.DLC=0;
  RxMessage.FMI=0;
  RxMessage.Data[0]=0x00;
  RxMessage.Data[1]=0x00;    

  CAN_Receive(CAN1,CAN_FIFO0, &RxMessage); //½ÓÊÕFIFO0ÖеÄÊý¾Ý  
 
  if((RxMessage.Data[0]==0x99)&&(RxMessage.Data[1]==0xbb))   
 // { LED1(0);LED2(1);LED3(1);}
   if((RxMessage.Data[0]==0x55)&&(RxMessage.Data[1]==0x77))   
   { 			
		 LED1( ON );			  // ÁÁ   D3
		Delay(0x200000);
		LED1( OFF );		  // Ãð

		LED2( ON );   //D2
		Delay(0x200000);
		LED2( OFF );

		LED3( ON );   //D2
		Delay(0x200000);
		LED3( OFF );  
	 }
   if((RxMessage.Data[0]==0x11)&&(RxMessage.Data[1]==0x33))   
  //{ LED1(1);LED2(1);LED3(0);}
	
   if((RxMessage.Data[0]==0x66)&&(RxMessage.Data[1]==0x77))   
  { 	
		LED1( ON );			  // ÁÁ   D3
		Delay(0x1000);
		LED1( OFF );		  // Ãð

		LED2( ON );   //D2
		Delay(0x1000);
		LED2( OFF );

		LED3( ON );   //D2
		Delay(0x1000);
		LED3( OFF );  
	}
	
		LED1( ON );			  // ÁÁ   D3
		Delay(0x50000);
		LED1( OFF );		  // Ãð

		LED2( ON );   //D2
		Delay(0x100000);
		LED2( OFF );

		LED3( ON );   //D2
		Delay(0x100000);
		LED3( OFF );  
  
} 



到了这里,关于CAN 设备通讯实验代码+HAL 与原生库分别实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 单片机编程-CAN通讯-理解与实现

    日期 作者 版本 说明 2023.02.03 Mr.Zheng V1.1 CAN通讯个人笔记,初版 最近刚刚做完一个较复杂项目,为强化巩固,准备写几篇笔记方便后续回溯,本篇重点是个人对CAN通讯的理解与实现,第一部分为CAN的模型架构,CAN的功能实现是第二部分,需要一定的编程基础,希望能够给初学

    2024年02月16日
    浏览(34)
  • 韦东山Linux驱动入门实验班(2)hello驱动---驱动层与应用层通讯,以及自动产生设备节点

    (1)学习韦东山老师的Linux,因为他讲的很精简,以至于很多人听不懂。接下来我讲介绍韦东山老师的驱动实验班的第二个Hello程序。 (2)注意,请先学习完视频再来看这个教程!本文仅供入门学习!如需深入,请搜索其他博客! (3)因为上一个教程已经讲的很详细了,所

    2024年02月05日
    浏览(49)
  • stm32f407单片机上通过HAL库实现can总线数据的收发

      最近在使用can总线,由于这个以前接触的比较少,所以调试代码的时候直接是下载的正点原子的例程,在这个基础上修改调试的。现在将调试中遇到的问题,总结一下,避免以后踩坑。目前写了一个查询方式的,一个中断方式的。项目代码下载地址: https://download.csdn.n

    2024年02月09日
    浏览(54)
  • 【STM32通讯系列--串口通讯】使用标准库、HAL库实现任意长度数据的收发(包含帧头、帧尾校验,配套完整开源程序)

    【数据组成】串口的通讯协议由开始位,数据位,校验位,结束位构成。 【数据结构】一般以一个低电平作为一帧数据的起始,接着跟随 8 位或者 9 位数据位,之后为校验位,分为奇校验,偶校验和无校验,最后以一个先高后低的脉冲表示结束位,长度可以设置为 0.5,1,

    2024年02月14日
    浏览(47)
  • STM32F103C8T6实现CAN通讯与直流编码电机转速闭环控制

    本次实验目的是通过CAN发送目标转速与转向信息,接收方在接到CAN数据流后开始对直流编码电机进行转速闭环控制。我会尽量说清每个函数,注释每一句代码,希望能对大家有所帮助。 CAN通讯基于STM32自带CAN通讯模块,配合库函数使用十分方便。关于CAN通讯可以参考站内大佬

    2023年04月08日
    浏览(42)
  • 创建大量栅格文件并分别写入像元数据:C++ GDAL代码实现

      本文介绍基于 C++ 语言 GDAL 库, 批量创建 大量栅格遥感影像文件,并将数据批量写入其中的方法。   首先,我们来明确一下本文所需实现的需求。已知我们对 大量遥感影像 进行了批量读取与数据处理操作——具体过程可以参考文章C++ GDAL提取多时相遥感影像中像素随

    2024年02月19日
    浏览(43)
  • CAN总线通讯协议学习

    s目录 CAN(controller Area Network) 控制器局域网 CAN通讯 CAN总线的数据帧 解析         CAN总线应用最多的是汽车领域,这里的控制器在汽车领域的专业术语是ECU.(electronic control unit)电子控制单元。可以看成一个超小型的计算机,内部集成了供电系统,单片机,驱动系统,是汽车领

    2024年02月05日
    浏览(35)
  • STM32——CAN通讯

    can通讯传输的是一种 差分信号 ,关于具体的硬件电路略。 1、发送流程 前置工作:如 时钟的开启、引脚的配置; CAN邮箱和模式等配置 参考下面或HAL库选择 选择一个 空置 的邮箱(判断空置:CAN_TSR的TMEx位); 在这个空置邮箱中按数据帧格式设置ID、数据长度以及要发送的数

    2024年03月09日
    浏览(49)
  • C C++ Java python 分别写出不同表白girlfriend的爱心动态代码实现

    C `` #include stdio.h #include stdlib.h #include windows.h void heart_animation() { int i, j, k; for (i = 1; i = 6; i++) { for (j = -3; j = 3; j++) { for (k = -4; k = 4; k++) { if (abs(j) + abs(k) i * 2) { printf(“I”); } else { printf(\\\" “); } } printf(”n\\\"); } Sleep(500); system(“cls”); } } int main() { heart_animation(); return 0; } `` C++ `` 动态

    2023年04月09日
    浏览(49)
  • stm32 cubemx can通讯(3)bsp_can

    stm32 cubemx can通讯(1)回环模式 stm32 cubemx can通讯(2)过滤器设置说明代码分析 根据前两篇文章已经能够实现can标准帧的收发,但是调用的函数没有标准化和可扩展性。 所以本文讲解bsp,在bsp中已经有了发送函数和接受回调函数的任务映射处理回调函数。 暂时(2023.8.10)还

    2024年02月13日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包