stm8s103 PWM的设置不难,但是很多人不注意选项字节这个问题,PWM是IO口的第二功能,要用ST Visual Programmer 修改选项字节。
只需要修改AFR0的功能就可以了
其中初始化代码如下
void TIM1_PWM_Init(unsigned int TIM1_CH1_Period,unsigned int TIM1_Pulse)
{
PC_DDR = 0xF0; // 配置PD端口的方向寄存器PD3输出
PC_CR1 = 0xF0; // 设置PD3为推挽输出
#if 1
TIM1_SMCR=0X00; //从模式功能 代设定
TIM1_ETR=0X00; //外部触发功能代设定
TIM1_SR1=0X00; //中断请求寄存器,清零
TIM1_SR2=0X00; //捕获标记寄存器
TIM1_BKR = 0X20;
TIM1_PSCRH=0; //预分频器高8位
TIM1_PSCRL=15; //预分频器低8位 15999+1分频 1ms
TIM1_ARRH=(unsigned char)(TIM1_CH1_Period>>8); //自动装载寄存器高
TIM1_ARRL=((unsigned char)TIM1_CH1_Period);
TIM1_CNTRH=0X00; //计数器清零
TIM1_CNTRL=0X00;
TIM1_CCER1 |= BIT0;
TIM1_CCMR1 |= 0x08;
TIM1_CCMR1 |= 0X60;
TIM1_CCR1H = 0;
TIM1_CCR1L = 200;
TIM1_CCER1 |= BIT4;
TIM1_CCMR2 |= 0x08;
TIM1_CCMR2 |= 0X60;
TIM1_CCR2H = 0;
TIM1_CCR2L = 200;
TIM1_BKR |= 0x80; //设置刹车寄存器
TIM1_IER = 0x00; //允许更新中断
TIM1_CR1 = 0x01; //计数器使能,开始计数
#endif
}
void SetTIM1_PWM_CH1_Cycle(unsigned int TIM1_Pulse)
{
TIM1_CCR1H = (unsigned char)(TIM1_Pulse>>8);
TIM1_CCR1L = ((unsigned char)TIM1_Pulse);
}