//ccr = 0~499
void setPWM1(unsigned short ccr){//PC1
TIM1_CCR1H = (unsigned char)(ccr>>8);
TIM1_CCR1L = (unsigned char)(ccr & 0xff);
}
void setPWM2(unsigned short ccr){//PC2
TIM1_CCR2H = (unsigned char)(ccr>>8);
TIM1_CCR2L = (unsigned char)(ccr & 0xff);
}
void setPWM3(unsigned short ccr){//PC3
TIM1_CCR3H = (unsigned char)(ccr>>8);
TIM1_CCR3L = (unsigned char)(ccr & 0xff);
}
void setPWM4(unsigned short ccr){//PC4
TIM1_CCR4H = (unsigned char)(ccr>>8);
TIM1_CCR4L = (unsigned char)(ccr & 0xff);
}
void TIM1_init(void)
{
TIM1_PSCRH = 0x01; // 8M系统时钟经预分频f=fck/(PSCR+1)
TIM1_PSCRL = 0x3F; // PSCR=0x13f,f=8M/(0x13F+1)=25 000Hz,每个计数周期40us
TIM1_ARRH = 0x01; // 自动重载寄存器ARR=0x01F4=500
TIM1_ARRL = 0xF4; // 每记数500次产生一次中断,即20ms
/**
* PWM 配置
*/
PC_DDR |= 0x1E; PC_CR1 |= 0x1E; PC_ODR &= ~0x1E;
TIM1_CCMR1 = 0x78;
TIM1_CCMR2 = 0x78;
TIM1_CCMR3 = 0x78;
TIM1_CCMR4 = 0x78;// Output mode PWM2.
// 通道 2 被设置成比较输出方式, OC2M = 111,为 PWM 模式 2, 向上计数时,若计数器小于比较值,为无效电平
TIM1_CCER1 = 0x33;
TIM1_CCER2 = 0x33;// CC polarity low,enable PWM output */
// CC2P = 1,低电平为有效电平
// CC2E = 1,开启输出引脚
//设置占空比
setPWM1(0); setPWM2(0);
setPWM3(0); setPWM4(0);
TIM1_EGR=0X01; //重新初始化计数器,并产生一个更新事件,可以不要
TIM1_BKR=0x80; //主输出使能,必须要有
TIM1_IER = 0x01; // 允许更新中断
TIM1_CR1 = 0x01; // 计数器使能,开始计数
}
//main()
int i = 0;
for(i=0;i<23;i++){ setPWM1(i*i);delay_ms(50); }
for(i=22;i>0;i--){ setPWM1(i*i);delay_ms(50); }
for(i=0;i<23;i++){ setPWM2(i*i);delay_ms(50); }
for(i=22;i>0;i--){ setPWM2(i*i);delay_ms(50); }
for(i=0;i<23;i++){ setPWM3(i*i);delay_ms(50); }
for(i=22;i>0;i--){ setPWM3(i*i);delay_ms(50); }
for(i=0;i<23;i++){ setPWM4(i*i);delay_ms(50); }
for(i=22;i>0;i--){ setPWM4(i*i);delay_ms(50); }
setPWM1(0); setPWM2(0);
setPWM3(0); setPWM4(0);
delay_ms(3000);*/
|