用寄存器模式写一段 STM32F103 8M时钟频率 配置 CAN 125K 程序
时间: 2024-12-20 15:24:35 浏览: 5
寄存器模式在STM32F103中用于配置硬件时钟和CAN通信参数,这是一种常见的编程技巧,通过直接操作硬件寄存器来设置系统状态。以下是配置STM32F103的8MHz时钟频率并启用CAN1以125kbps速率工作的示例程序片段:
```c
#include "stm32f10x.h" // 包含STM32F103的头文件
// 初始化函数
void SystemClock_Config(void) {
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
// 首先禁用所有时钟源
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_CLEAR_FLAG(PWR_FLAG_HLI); // 清除低电压检测标志
// 启动HSE时钟,并允许最大振荡时间
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 8; // M = (SystemCoreClock / HSE_Frequency) - 1
RCC_OscInitStruct.PLL.PLLN = 336; // N = (72 * MHz) + 1
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 7;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
while(1); // 如果配置失败,则进入无限循环
}
// 将HSE作为系统时钟源
RCC_ClkInitStruct.ClockType = 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_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK) {
while(1); // 如果时钟配置失败,则进入无限循环
}
}
// CAN初始化函数
void CAN1_Init(uint32_t freq) {
GPIO_InitTypeDef GPIO_InitStruct;
// 配置CAN RX/TX GPIO
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF11_CAN1;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
// 初始化CAN模块
CAN_DeInit(CAN1); // 清除CAN1的所有数据
CAN_InitStructure.CAN_NormalMode = ENABLE;
CAN_InitStructure.CAN_SJW = CAN_SJW_1T;
CAN_InitStructure.CAN_BTR = CAN_BTR_15Samples;
CAN_InitStructure.CAN_Mode = CAN_ModeNormal;
CAN_InitStructure.CAN_Prescaler = RCC_APB1PeriphClockGet() / freq; // 根据需要的波特率设置分频系数
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;
CAN_InitStructure.CAN_TXFP = DISABLE;
HAL_CAN_Init(CAN1, &CAN_InitStructure);
// 开启CAN模块
CAN_Cmd(CAN1, ENABLE);
}
int main(void) {
SystemClock_Config(); // 设置系统时钟到8MHz
CAN1_Init(1000000); // 配置CAN1,125kbps波特率
// 其他主函数代码...
return 0;
}
```
阅读全文