最近一个项目,用的是STM8S003F3这款小型的MCU,使用TIM1_CH1 TIM_CH2作为PWM输出时,遇到了问题,代码下载后,PWM是没有任何输出的。用示波器看,应该是PWM没有任何输出。
首先在网上找了下资料,又看了官方的例程,感觉代码没有问题。后来仔细查看问题,终于找到解决的方案。
原来根据STM8S003F3的数据手册,需要配置一个选项字节才能使能TIM1_CH1与TIM1_CH2。
配置的方法有两种:
(1)使用STVP(STM32与STM8)烧写的软件,在烧写固件时,配置一下,下载到芯片,其实这个保存在DataFlash中,理论上配置一次,再使用ST-LINK下载,就一直生效。
(2)方法二,STM8S的固件库里,是有编程这个选项字节的功能的,只需要调用,在初始化时把相应的字节编程一下即可,重启生效,然后就可以一直使用了。
#ifdef __ENABLE_TIM1_CH1_CH2__
#define TIM1_OptionAddr (0x4803) //OPT2 BIT1
void Enable_TIM1_CH1CH2_OptionByte(void)
{
uint16_t TIM1_Option_status;/*记录激活备选功能Beep/TIM2_CH1的状态*/
TIM1_Option_status = FLASH_ReadOptionByte(TIM1_OptionAddr);
/* ARF0 BIT: 1 enable TIM1 CH1 CH2 */
if((TIM1_Option_status&0x0100) == 0x00)
{
FLASH_Unlock(FLASH_MEMTYPE_DATA);
FLASH_ProgramOptionByte(TIM1_OptionAddr, (uint8_t)(0x01));
FLASH_Lock(FLASH_MEMTYPE_DATA);
/*使能TIM1 CH1 CH2 PWM */
Delay_ms(10);
WWDG_SWReset();
}
}
#endif
STM8S003F3的TIM1 配置PWM的代码如下:
void TIM1_PWM_Init(void)
{
GPIO_Init(PWM1_GPIO_PORT, PWM1_GPIO_PINS, GPIO_MODE_OUT_PP_LOW_FAST);
GPIO_Init(PWM2_GPIO_PORT, PWM2_GPIO_PINS, GPIO_MODE_OUT_PP_LOW_FAST);
GPIO_Init(PWM3_GPIO_PORT, PWM3_GPIO_PINS, GPIO_MODE_OUT_PP_LOW_FAST);
GPIO_Init(PWM4_GPIO_PORT, PWM4_GPIO_PINS, GPIO_MODE_OUT_PP_LOW_FAST);
CLK_PeripheralClockConfig(CLK_PERIPHERAL_TIMER1,ENABLE);
TIM1_DeInit();
TIM1_Cmd(DISABLE);
TIM1_TimeBaseInit(TIM1_Prescaler0, TIM1_COUNTERMODE_UP, T1_MAXPWM-1, 0);//16M/200=80K
/* Channel 1, 2,3 and 4 Configuration in PWM mode */
/*
TIM1_OCMode = TIM1_OCMODE_PWM2
TIM1_OutputState = TIM1_OUTPUTSTATE_ENABLE
TIM1_OutputNState = TIM1_OUTPUTNSTATE_DISABLE
TIM1_Pulse = CCR1_Val
TIM1_OCPolarity = TIM1_OCPOLARITY_LOW
TIM1_OCNPolarity = TIM1_OCNPOLARITY_HIGH
TIM1_OCIdleState = TIM1_OCIDLESTATE_SET
TIM1_OCNIdleState = TIM1_OCIDLESTATE_RESET
*/
TIM1_OC1Init(TIM1_OCMODE_PWM2, TIM1_OUTPUTSTATE_ENABLE, TIM1_OUTPUTNSTATE_DISABLE,
100, TIM1_OCPOLARITY_LOW, TIM1_OCNPOLARITY_HIGH, TIM1_OCIDLESTATE_SET,
TIM1_OCNIDLESTATE_RESET);
TIM1_OC2Init(TIM1_OCMODE_PWM2, TIM1_OUTPUTSTATE_ENABLE, TIM1_OUTPUTNSTATE_DISABLE,
100, TIM1_OCPOLARITY_LOW, TIM1_OCNPOLARITY_HIGH, TIM1_OCIDLESTATE_SET,
TIM1_OCNIDLESTATE_RESET);
TIM1_OC3Init(TIM1_OCMODE_PWM1, TIM1_OUTPUTSTATE_ENABLE, TIM1_OUTPUTNSTATE_DISABLE,
100, TIM1_OCPOLARITY_LOW, TIM1_OCNPOLARITY_HIGH, TIM1_OCIDLESTATE_SET,
TIM1_OCNIDLESTATE_RESET);
TIM1_OC4Init(TIM1_OCMODE_PWM1, TIM1_OUTPUTSTATE_ENABLE,
180, TIM1_OCPOLARITY_LOW, TIM1_OCIDLESTATE_RESET);
TIM1_OC1PreloadConfig(ENABLE);
TIM1_OC2PreloadConfig(ENABLE);
TIM1_OC3PreloadConfig(ENABLE);
TIM1_OC4PreloadConfig(ENABLE);
TIM1_CCxCmd(TIM1_CHANNEL_1, ENABLE);
TIM1_CCxCmd(TIM1_CHANNEL_2, ENABLE);
TIM1_CCxCmd(TIM1_CHANNEL_3, ENABLE);
TIM1_CCxCmd(TIM1_CHANNEL_4, ENABLE);
TIM1_CtrlPWMOutputs(ENABLE);
TIM1_Cmd(ENABLE);
}
经过测试,STM8S003F3 的Timer1 四个PWM通道输出均正常了。看来,小小的MCU,还是需要深入研究并使用的。