本帖最后由 11yichengming 于 2015-7-8 09:32 编辑
/* MAIN.C file
function : TIM1定时器周期中断实现LED1周期为2S的亮灭;TIM2用PWM波实现同样的功能;
TIM1 10ms定时器周期中断;
TIM2_CH3 PD2 输出周期为1Hz的PWM;
problem :
(1) 使用默认的内部2M时钟,实现同样的功能上频率不一样;
(2) 单独测试TIM1和TIM2实现的功能是按预期设定来的;
*/
#include<stm8s003f3p.h>
_Bool PD2 @PD_ODR:2;
_Bool PC7 @PC_ODR:7;
#define LED1 PD2
#define LED2 PC7
void Init_GPIO(void)
{
/*LED/PWM 配置为推挽输出*/
PD_DDR |= 0X04; //PD2--PWM输出---连接LED1
PD_CR1 |= 0X04;
PD_CR2 &= 0XFD;
PC_DDR |= 0X80; //PC7---LED2;
PC_CR1 |= 0X80;
PC_CR2 &= 0X7F;
}
void Init_TIM1(void)
{
_asm("sim");
TIM1_IER = 0x00;
TIM1_CR1 = 0x00;
TIM1_EGR |= 0x01;
TIM1_PSCRH = 49/256; //2M系统时钟经预分频f=fck/(PSCR+1) TIM1 为16位分频器
TIM1_PSCRL = 49%256; //f=2M/(49+1)=40000Hz,每个计数周期1ms
TIM1_CNTRH = 0x00;
TIM1_CNTRL = 0x00;
TIM1_ARRH = 400/256; // 自动重载寄存器ARR=400
TIM1_ARRL = 400%256; // 每记数400次产生一次中断,即10ms
TIM1_CR1 |= 0x81;
TIM1_IER |= 0x01;
}
void Init_TIM2(void)
{
TIM2_IER = 0x00; //禁止各种中断
TIM2_EGR |= 0X01; //如果要 新的 预分频值生效,必须产生更新事件
TIM2_CCMR3 |= 0X60; //设置定时器2三通道(PD2)输出比较三模式
TIM2_CCMR3 |= 0X08; //输出比较3预装载使能
TIM2_CCER2 |= 0x03; //通道3使能,低电平有效,配置为输出
//初始化时钟分频器为1,即计数器的时钟频率为Fmaster=2M/64=0.125MHZ
TIM2_PSCR = 0X05;
//初始化自动装载寄存器,决定PWM 方波的频率,Fpwm=0.0625M/62500=1HZ
TIM2_ARRH = 62500/256;
TIM2_ARRL = 62500%256;
//初始化比较寄存器,决定PWM 方波的占空比:50%
TIM2_CCR3H = 31250/256;
TIM2_CCR3L = 31250%256;
//启动计数;更新中断失能
TIM2_CR1 = 0x01;
}
main()
{
Init_GPIO();
Init_TIM1();
Init_TIM2();
LED1 = 1;LED2 = 1;
_asm("rim");
while (1);
}
@far @interrupt void TIM1_UPD_OVF_TRG_BRK_IRQHandler(void)
{
static unsigned int i = 0;
TIM1_SR1 &=~(0x01);
++i;
if(100 == i){
LED2 = ~LED2;
i = 0;
}
}
|