1定义时钟
2定义按键
按键上拉电阻
3开启串口
4打开CAN(具体什么意思上一篇讲了)
5生成代码
/* USER CODE BEGIN Header */
/********************************************************************************* @file : main.c* @brief : Main program body******************************************************************************* @attention** Copyright (c) 2024 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 */
#include "stdio.h"
/* 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 */
/*** CAN 发送一组数据* 数据 长度*/
uint8_t can_send_msg( uint8_t *data, uint8_t len )
{//发的结构体CAN_TxHeaderTypeDef can_tx;can_tx.DLC=len; // 数据长度代码can_tx.ExtId=0x00;// 扩展标识符can_tx.IDE=CAN_ID_EXT;// 标识符类型为扩展帧 //标识符的长度can_tx.RTR=CAN_RTR_DATA;// 远程传输请求为数据帧can_tx.StdId=0x12;// 标准标识符 //can的ID//can_tx.TransmitGlobalTime=ENABLE;// 使用全局时间 ENABLE开启 DISABLE关闭 时间戳uint32_t as=CAN_TX_MAILBOX0;if(HAL_CAN_AddTxMessage(&hcan,&can_tx,data,&as)==HAL_OK){int as1=HAL_CAN_GetTxMailboxesFreeLevel(&hcan);char aa[28];sprintf(aa,"数据发送成功,邮箱个数为:%d\n",as1);HAL_UART_Transmit(&huart1,(uint8_t*)aa,27,50);}while (HAL_CAN_GetTxMailboxesFreeLevel(&hcan) != 3); /* 等待发送完成,所有邮箱为空 */return 0;
}/*** CAN 接收数据查询// 数据*/
void can_receive_msg( uint8_t *data )
{//接收的结构体// 声明一个变量来存储接收到的消息的头部信息CAN_RxHeaderTypeDef can_rx;//can_rx.DLC // 数据长度//can_rx.ExtId //扩展标识符//can_rx.FilterMatchIndex// 过滤器匹配索引//can_rx.IDE // 标识符类型为扩展帧//can_rx.RTR // 远程传输请求为数据帧//can_rx.StdId; // 标准标识符//can_rx.Timestamp ; // 时间戳if(HAL_CAN_GetRxMessage(&hcan, CAN_RX_FIFO0, &can_rx, data)== HAL_OK){char aa[28]={"接收成功\n"};HAL_UART_Transmit(&huart1,(uint8_t*)aa,9,50);}else{char aa[28]={"接收失败\n"};HAL_UART_Transmit(&huart1,(uint8_t*)aa,9,50);}
}
/* USER CODE END 0 *//*** @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 */CAN_FilterTypeDef sFilterConfig;//配置CAN过滤器sFilterConfig.FilterBank = 0; /* 过滤器0 */sFilterConfig.FilterMode = CAN_FILTERMODE_IDMASK;sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT;sFilterConfig.FilterIdHigh = 0x0000; /* 32位ID */sFilterConfig.FilterIdLow = 0x0000;sFilterConfig.FilterMaskIdHigh = 0x0000; /* 32位MASK */sFilterConfig.FilterMaskIdLow = 0x0000;sFilterConfig.FilterFIFOAssignment = CAN_FILTER_FIFO0; /* 过滤器0关联到FIFO0 */sFilterConfig.FilterActivation = CAN_FILTER_ENABLE; /* 激活滤波器0 */sFilterConfig.SlaveStartFilterBank = 14;// 过滤器配置 if ( HAL_CAN_ConfigFilter( &hcan, &sFilterConfig ) != HAL_OK ){return 2;}// 启动CAN外围设备 if ( HAL_CAN_Start( &hcan ) != HAL_OK ){return 3;}/* USER CODE END 2 *//* Infinite loop *//* USER CODE BEGIN WHILE */while (1){if(HAL_GPIO_ReadPin(GPIOE,GPIO_PIN_4)== GPIO_PIN_SET){HAL_Delay(20);if(HAL_GPIO_ReadPin(GPIOE,GPIO_PIN_4)==HAL_OK){char a[]={"按键按下了\n"};HAL_UART_Transmit(&huart1,(uint8_t*)a,11,50);uint8_t tx_data[8] = {"ABCDEFGH"}; // 消息数据uint8_t rx_data[8]; // 接收数据缓冲区can_send_msg( tx_data, 8 );if(HAL_CAN_GetRxFifoFillLevel(&hcan ,CAN_RX_FIFO0)){can_receive_msg( rx_data );}else{char aa[28]={"无数据\n"};HAL_UART_Transmit(&huart1,(uint8_t*)aa,9,50);}HAL_Delay(500);HAL_UART_Transmit(&huart1,rx_data,8,500);}}/* USER CODE END WHILE *//* USER CODE BEGIN 3 */}/* 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_HSE;RCC_OscInitStruct.HSEState = RCC_HSE_ON;RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;RCC_OscInitStruct.HSIState = RCC_HSI_ON;RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;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 */
6编写过程
1编写接收函数
*** CAN 接收数据查询// 数据*/
void can_receive_msg( uint8_t *data )
{//接收的结构体// 声明一个变量来存储接收到的消息的头部信息CAN_RxHeaderTypeDef can_rx;//can_rx.DLC // 数据长度//can_rx.ExtId //扩展标识符//can_rx.FilterMatchIndex// 过滤器匹配索引//can_rx.IDE // 标识符类型为扩展帧//can_rx.RTR // 远程传输请求为数据帧//can_rx.StdId; // 标准标识符//can_rx.Timestamp ; // 时间戳if(HAL_CAN_GetRxMessage(&hcan, CAN_RX_FIFO0, &can_rx, data)== HAL_OK){char aa[28]={"接收成功\n"};HAL_UART_Transmit(&huart1,(uint8_t*)aa,9,50);}else{char aa[28]={"接收失败\n"};HAL_UART_Transmit(&huart1,(uint8_t*)aa,9,50);}
}
2编写发送函数
/*** CAN 发送一组数据* 数据 长度*/
uint8_t can_send_msg( uint8_t *data, uint8_t len )
{//发的结构体CAN_TxHeaderTypeDef can_tx;can_tx.DLC=len; // 数据长度代码can_tx.ExtId=0x00;// 扩展标识符can_tx.IDE=CAN_ID_EXT;// 标识符类型为扩展帧 //标识符的长度can_tx.RTR=CAN_RTR_DATA;// 远程传输请求为数据帧can_tx.StdId=0x12;// 标准标识符 //can的ID//can_tx.TransmitGlobalTime=ENABLE;// 使用全局时间 ENABLE开启 DISABLE关闭 时间戳uint32_t as=CAN_TX_MAILBOX0;if(HAL_CAN_AddTxMessage(&hcan,&can_tx,data,&as)==HAL_OK){int as1=HAL_CAN_GetTxMailboxesFreeLevel(&hcan);char aa[28];sprintf(aa,"数据发送成功,邮箱个数为:%d\n",as1);HAL_UART_Transmit(&huart1,(uint8_t*)aa,27,50);}while (HAL_CAN_GetTxMailboxesFreeLevel(&hcan) != 3); /* 等待发送完成,所有邮箱为空 */return 0;
}
3配置过滤器(不配置不可接收数据)
CAN_FilterTypeDef sFilterConfig;//配置CAN过滤器sFilterConfig.FilterBank = 0; /* 过滤器0 */sFilterConfig.FilterMode = CAN_FILTERMODE_IDMASK;sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT;sFilterConfig.FilterIdHigh = 0x0000; /* 32位ID */sFilterConfig.FilterIdLow = 0x0000;sFilterConfig.FilterMaskIdHigh = 0x0000; /* 32位MASK */sFilterConfig.FilterMaskIdLow = 0x0000;sFilterConfig.FilterFIFOAssignment = CAN_FILTER_FIFO0; /* 过滤器0关联到FIFO0 */sFilterConfig.FilterActivation = CAN_FILTER_ENABLE; /* 激活滤波器0 */sFilterConfig.SlaveStartFilterBank = 14;// 过滤器配置 if ( HAL_CAN_ConfigFilter( &hcan, &sFilterConfig ) != HAL_OK ){return 2;}// 启动CAN外围设备 if ( HAL_CAN_Start( &hcan ) != HAL_OK ){return 3;}
4编写按键实现收发数据
while (1){if(HAL_GPIO_ReadPin(GPIOE,GPIO_PIN_4)== GPIO_PIN_SET){HAL_Delay(20);if(HAL_GPIO_ReadPin(GPIOE,GPIO_PIN_4)==HAL_OK){char a[]={"按键按下了\n"};HAL_UART_Transmit(&huart1,(uint8_t*)a,11,50);uint8_t tx_data[8] = {"ABCDEFGH"}; // 消息数据uint8_t rx_data[8]; // 接收数据缓冲区can_send_msg( tx_data, 8 );if(HAL_CAN_GetRxFifoFillLevel(&hcan ,CAN_RX_FIFO0)){can_receive_msg( rx_data );}else{char aa[28]={"无数据\n"};HAL_UART_Transmit(&huart1,(uint8_t*)aa,9,50);}HAL_Delay(500);HAL_UART_Transmit(&huart1,rx_data,8,500);}}/* USER CODE END WHILE *//* USER CODE BEGIN 3 */}/* USER CODE END 3 */
}
效果
注意
1过滤器
主页中有免费的CAN资料和项目文件