#include"canshu.h" uint t; uchar time2_2h=4,time2_2l=4; void TIM2_Init() { TIM2_CCMR2 = TIM2_CCMR2 | 0x70;// Output modePWM2. //通道2被设置成比较输出方式 // OC2M = 111,为PWM模式2, // 向上计数时,若计数器小于比较值,为无效电平 // 即当计数器在0到比较值时,输出为1,否则为0 TIM2_CCMR1 = TIM2_CCMR1 | 0x70; TIM2_CCMR3 = TIM2_CCMR3 | 0x70; TIM2_CCER1 = TIM2_CCER1 | 0x33;// CC polarity low,enable PWMoutput */ // CC2P = 1,低电平为有效电平 // CC2E = 1,开启输出引脚 TIM2_CCER2 = TIM2_CCER2 | 0x03; //初始化自动装载寄存器,决定PWM方波的频率,Fpwm=16000000/1000=16kHZ TIM2_ARRH = 16000/255; TIM2_ARRL = 16000%255; TIM2_CCR1H =time2_2h; TIM2_CCR1L = time2_2l=4; //初始化比较寄存器,决定PWM方波的占空比 TIM2_CCR2H =1000/255; TIM2_CCR2L =1000%255; TIM2_CCR3H = 1000/255; TIM2_CCR3L = 1000%255; //初始化时钟分频器为1,即计数器的时钟频率为Fmaster=4MHZ TIM2_PSCR =0x00;//因为用了继电器,所以哟分频,可到0x08,256分频 //启动计数 TIM2_CR1 = TIM2_CR1 | 0x01; } //外部中断触发 void exit_init() { PC_DDR&=~0x04; PC_CR1|=0x04; PC_CR2|=0x04; EXTI_CR1|= 0x10; } #pragma vector=0x07 // 这里很关键!看下面说明。 __interrupt void EXTI_PC1(void) { asm("sim"); switch(EXTI_CR1) { case 0x10:EXTI_CR1=0x20;exit_flag=1;break; case 0x20:EXTI_CR1=0x10;exit_flag=2;break; default :exit_flag=0;break; } if(exit_flag==2) { t++; exit_flag=0; if(t%10==0) { ulong chaju; now_nus=TIM4_CNTR; now_ms=cishu; chaju_ms=now_ms-last_ms; if(cishu_flag==1) { cishu_flag=0; chaju_ms=30000+now_ms-last_ms; } chaju_nus=now_nus-last_nus; chaju=chaju_ms*250+chaju_nus; now_rads=(1250000/chaju); last_nus=now_nus; last_ms=now_ms; last_rads[rads_flag++]=now_rads; if(rads_flag==10) rads_flag=0; pid_error=now_rads-last_radss; pid_error1=last_radss-last_radsss; last_radsss=last_radss; last_radss =now_rads; } } asm("rim"); } #pragma vector=TIM2_OVR_UIF_vector __interrupt void TIM3_OVF_IRQHandler(void) { TIM2_SR1 = 0x00; ds1820_flag=1; } //定时器2产生60s的中断 void TIM2_time() { TIM2_EGR=0x01; //手动产生更新事件,重新初始化计数器,并允许产生一个更新事件 //设置定时器初值 TIM2_CNTRH=0; //不能使用TIM3_CNTR直接设值, TIM2_CNTRL=0; //设定自动重装寄存器值 //这里得注意不能使用TIM2_ARR的方式进行设值,TIM2是十六位的。 //如TIM2_ARR=0xFA,实际上是赋给高字节了,TIM2_ARRH=0xFA,而不是想象中的赋给低字节。 TIM2_ARRH=0x72; //488hz 488 /29280 = 60s (1S) TIM2_ARRL=0x60; //0x007d 意味着每产生一次中断时间为60S TIM2_PSCR=0x0f; //预分频32275 TIM2_IER=0x01; //中断允许位使能 TIM2_CR1=0x01; //使能计时器 }
|