选择TIM3_CH2B输出PWM,其引脚功能配置如下图所示:
引脚功能配置代码如下:
//Timer3 Port端口配置
void App_Timer3PortCfg(void)
{
stc_gpio_cfg_t stcTIM3Port;
DDL_ZERO_STRUCT(stcTIM3Port);
Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE); //端口外设时钟使能
stcTIM3Port.enDir = GpioDirOut;
Gpio_Init(GpioPortB, GpioPin1, &stcTIM3Port); //PB01设置为TIM3_CH2B
Gpio_SetAfMode(GpioPortB,GpioPin1,GpioAf3);
}
//Timer3 配置
void App_Timer3Cfg(uint16_t u16Period, uint16_t u16CHxACompare, uint16_t u16CHxBCompare)
{
uint16_t u16CntValue;
uint8_t u8ValidPeriod;
stc_tim3_mode23_cfg_t stcTim3BaseCfg;
stc_tim3_m23_compare_cfg_t stcTim3PortCmpCfg;
DDL_ZERO_STRUCT(stcTim3BaseCfg); //结构体初始化清零
DDL_ZERO_STRUCT(stcTim3PortCmpCfg);
Sysctrl_SetPeripheralGate(SysctrlPeripheralTim3, TRUE); //Timer3外设时钟使能
stcTim3BaseCfg.enWorkMode = Tim3WorkMode2; //三角波模式
stcTim3BaseCfg.enCT = Tim3Timer; //定时器功能,计数时钟为内部PCLK
stcTim3BaseCfg.enPRS = Tim3PCLKDiv1; //PCLK
stcTim3BaseCfg.enCntDir = Tim3CntUp; //向上计数,在三角波模式时只读
stcTim3BaseCfg.enPWMTypeSel = Tim3IndependentPWM; //独立输出PWM
stcTim3BaseCfg.enPWM2sSel = Tim3DoublePointCmp; //单点比较功能
stcTim3BaseCfg.bOneShot = FALSE; //循环计数
stcTim3BaseCfg.bURSSel = FALSE; //上下溢更新
Tim3_Mode23_Init(&stcTim3BaseCfg); //TIM3 的模式0功能初始化
Tim3_M23_ARRSet(u16Period, TRUE); //设置重载值,并使能缓存
Tim3_M23_CCR_Set(Tim3CCR2B, u16CHxBCompare); //设置CH2比较值B
stcTim3PortCmpCfg.enCHxBCmpCtrl = Tim3PWMMode2; //OCREFB输出控制OCMB:PWM模式2(PWM互补模式下也要设置,避免强制输出)
stcTim3PortCmpCfg.enCHxBPolarity = Tim3PortPositive; //正常输出
stcTim3PortCmpCfg.bCHxBCmpBufEn = TRUE; //B通道缓存控制使能
stcTim3PortCmpCfg.enCHxBCmpIntSel = Tim3CmpIntNone; //B通道比较中断控制:无
u8ValidPeriod = 1; //事件更新周期设置,0表示三角波每半个周期更新一次,每+1代表延迟半个周期
Tim3_M23_SetValidPeriod(u8ValidPeriod); //间隔周期设置
u16CntValue = 0;
Tim3_M23_Cnt16Set(u16CntValue); //设置计数初值
}
系统时钟源配置 选择内部时钟,PCLK/4 可得时间为1us
///< 时钟初始化
void App_ClockInit(void)
{
stc_sysctrl_clk_cfg_t stcCfg;
///< 开启FLASH外设时钟
Sysctrl_SetPeripheralGate(SysctrlPeripheralFlash, TRUE);
///<========================== 时钟初始化配置 ===================================
///< 因要使用的时钟源HCLK小于24M:此处设置FLASH 读等待周期为0 cycle(默认值也为0 cycle)
Flash_WaitCycle(FlashWaitCycle0);
///< 时钟初始化前,优先设置要使用的时钟源:此处设置RCH为4MHz
Sysctrl_SetRCHTrim(SysctrlRchFreq4MHz);
///< 选择内部RCH作为HCLK时钟源;
stcCfg.enClkSrc = SysctrlClkRCH;
///< HCLK SYSCLK/1
stcCfg.enHClkDiv = SysctrlHclkDiv1;
///< PCLK 为HCLK/1
stcCfg.enPClkDiv = SysctrlPclkDiv4;
///< 系统时钟初始化
Sysctrl_ClkInit(&stcCfg);
}
主函数中初始化
int32_t main(void)
{
App_ClockInit();
App_Timer3PortCfg();
App_Timer3Cfg(0x19, 0xD, 0xD); // 周期 25 频率约为38.5KHz
Tim3_M23_EnPWM_Output(TRUE, FALSE); //端口输出使能
Tim3_M23_Run(); //运行
while(1);
}
示波器频率为38.53KHz