#申请原创# 2022年底在沁恒官网看到CH32F205R的数据资料后,被这颗IC的强大外设吸引,于是果断填写样片申请.了解到CH32F205R与CH32F103R系列的引脚是兼容的,正好在之前有做过一块工业设备物联网数据采集的PCB板(小批量生产了400片),小修改一下重新打样做为F205R的测试平台.详细功能见附件的电路原理图.
今天要测试的第一个功能是PWM输出,后续将使用PWM输出配合NTC温度采样去控制无刷电机.
PWM使用的是PA1,连接至内部定时器2的通道2,初始化步骤:
1.打开PA端口和定时器2的时钟.
2.配置PA1为复用功能.
3.设置TIM2的时钟分频,计数周期,重装载值.
4.设置通道2的PWM模式,点空比.
5.打开TIM2的PWM输出.
6.使能TIM2定时器.
#include "use_pwm.h"
#define PRESCALER 3 //TIM2时钟分频
#define PWMFREQ 20000 //PWM频率20KHz
#define TIM2_ARR SystemCoreClock/PRESCALER/PWMFREQ //TIM2 ARR装载值
void USE_TIM2PWM_Init( )
{
GPIO_InitTypeDef GPIO_InitStructure = {0};
TIM_OCInitTypeDef TIM_OCInitStructure = {0};
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure = {0};
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA, ENABLE );
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE );
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init( GPIOA, &GPIO_InitStructure );
TIM_TimeBaseInitStructure.TIM_Period = TIM2_ARR - 1;
TIM_TimeBaseInitStructure.TIM_Prescaler = PRESCALER - 1;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit( TIM2, &TIM_TimeBaseInitStructure );
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = TIM2_ARR/2 - 1;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC2Init( TIM2, &TIM_OCInitStructure );
TIM_CtrlPWMOutputs( TIM2, ENABLE );
TIM_OC1PreloadConfig( TIM2, TIM_OCPreload_Disable );
TIM_ARRPreloadConfig( TIM2, ENABLE );
TIM_Cmd( TIM2, ENABLE );
}
编译后下载至MCU,观察示波器的结果与预想的一致.PWM频率为20KHz,占空比50%.
示波器实拍图
示波器截图
|