大佬,您好。我也想用定時器中斷,但是不知道為什么不行,下面是相關代碼,您有時間幫我看一下好嗎?
這是time.c代碼:
#include "timer.h"
static int i = 0 ;
u32 count0=0;u32 count1=0;
//通用定時器中斷初始化
//這里時鐘選擇為APB1的2倍,而APB1為36M
//arr:自動重裝值。
//psc:時鐘預分頻數
//這里使用的是定時器2
void Timer2_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //上拉輸入
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //50M時鐘速度
GPIO_Init(GPIOA, &GPIO_InitStructure);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); //時鐘使能
TIM_DeInit(TIM2);
TIM_TimeBaseStructure.TIM_Period = arr; //設置在下一個更新事件裝入活動的自動重裝載寄存器周期的值 計數到5000為500ms arr
TIM_TimeBaseStructure.TIM_Prescaler =psc; //設置用來作為TIMx時鐘頻率除數的預分頻值 10Khz的計數頻率
TIM_TimeBaseStructure.TIM_ClockDivision = 0; //設0置時鐘分割:TDTS = Tck_tim psc
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上計數模式
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); //根據TIM_TimeBaseInitStruct中指定的參數初始化TIMx的時間基數單位
TIM_ETRClockMode2Config(TIM2, TIM_ExtTRGPSC_OFF, TIM_ExtTRGPolarity_NonInverted, 0); //設置為外部計數模式
TIM_SetCounter(TIM2, 0); //計數器清零
TIM_Cmd(TIM2, ENABLE); //使能TIMx外設
}
void TIM2_IRQHandler()
{
int a = 0;
if(TIM_GetITStatus(TIM2,TIM_IT_Update)!=RESET) //產生一次中斷為1s
{
if(GPIOA->IDR& GPIO_IDR_IDR0)//判斷PA0是否為高電平
{
i++;
printf("i:%d\r\n",i);
}
else
{
a++;
printf("i:%d\r\n",a);
}
TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
}
}
下面是主函數main.c
int main(void)
{
NVIC_Configuration() ;
RCC_ClocksTypeDef RCC_Clocks;
RCC_Configuration();
RCC_GetClocksFreq(&RCC_Clocks);
Timer2_Init(0xffff,0);
USART1_Init(9600);
delay_init();
LED_Init();
DHT11_Init();
DS1302_Init();
DS1302_Write_Time();
DS1302_Read_Time();
display1();
while(1)
{
// DS1302_Get_Time(time);
// display_time(time);
//
// DHT11_Read_Data(&temperature,&humidity) ;
// display_dht11(temperature,humidity);
sprintf((char *)display,"FS: ") ;
LCD_Print(1,4,display) ;
Speed=getspeed();
|