图1 TIM1高级定时器的功能
stm8s的pwm功能可由其高级定时器TIM1配置输出。TIM1有四个输出通道,我们选择其中一路TIM1-CH4,默认情况下,其对应的CPU端口在PC4,如图2 AFR7位。图2 TIM1映射端口
接下来我们通过软件编程介绍一下TIM1的pwm技术(假设我们主时钟使用8M)。#define BIT(n) (1<<(n))
//(1)设置端口P4GPIOC->DDR |= 0X10; //PC4设输出模式
GPIOC->CR1 |= 0X01; // PC4设为推挽输出
GPIOC->CR2 = 0X0;
//(2)设置TIM1TIM1->CR1 &= ~BIT(0); //关闭TIM1
TIM1->PSCRH = 0;
TIM1->PSCRL = 0x40; //64分频 8M/64=0.125MTIM1->ARRH = 0Xf4;
TIM1->ARRL = 0X23; //0.125MHz/(62499+1) = 2Hz
TIM1->CR1 |= BIT(7); //使能ARP,边沿对齐,向上计数TIM1->EGR |= BIT(0); //更新TIM1,使PSC有效
TIM1->EGR|=0x20;//重新初始化TIM1
TIM1->CCR4H = 0X7a;
TIM1->CCR4L = 0X12; //占空比50%TIM1->CCMR4 = 0X68; //配置TIM1_CH4为PWM1模式输出
TIM1->CCER2 |= BIT(4); //Enable TIM1_CH4 channel
TIM1->BKR |= BIT(7);
TIM1->CR1 |= BIT(0); //使能TIM1通过以软件配置,使得CPU输出pwm波形。