第十个实验 TIMER定时器的配置及使用 代码亲测可用

xiaoxiao2021-02-28  43

#include "stm32f10x.h" uint16_t TIM_Count; #define LED1 1 #define LED3 3 void LEDXToggle(uint8_t ledx); void TIM2_delay(u16 time); int main() {   GPIO_InitTypeDef  GPIO_InitStructure;      RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE);   GPIO_InitStructure.GPIO_Pin =GPIO_Pin_13;//?????GPIO??     GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //?????????????           GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;//???????50MHZ             GPIO_Init(GPIOC, &GPIO_InitStructure);//?????,???GPIO       TIM_TimeBaseInitTypeDef  TIM_BaseInitStructure;   //¶¨ÒåÒ»¸ö¶¨Ê±Æ÷½á¹¹Ìå±äÁ¿   RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);    //ʹÄܶ¨Ê±Æ÷2   TIM_DeInit( TIM2);//½«IM2¶¨Ê±Æ÷³õʼ»¯Î»¸´Î»Öµ   TIM_InternalClockConfig(TIM2);//ÅäÖà TIM2 ÄÚ²¿Ê±ÖÓ   TIM_BaseInitStructure.TIM_Period = 1000;//ÉèÖÃ×Ô¶¯ÖØÔؼĴæÆ÷ֵΪ×î´óÖµ 0~65535Ö®¼ä  1000000/1000=1000us=1ms                //TIM_Period£¨TIM1_ARR£©=1000£¬¼ÆÊýÆ÷ÏòÉϼÆÊýµ½1000ºó²úÉú¸üÐÂʼþ£¬¼ÆÊýÖµ¹éÁã Ò²¾ÍÊÇ 1MS²úÉú¸üÐÂʼþÒ»´Î   TIM_BaseInitStructure.TIM_Prescaler = 71;//×Ô¶¨ÒåÔ¤·ÖƵϵÊý£¬Ìṩ¸ø¶¨Ê±Æ÷µÄʱÖÓ 0~65535Ö®¼ä               //ÉèÖÃÔ¤·ÖƵÆ÷·ÖƵϵÊý71£¬¼´CK_INT=72M, TIM1_CLK=72/72=1MHz   TIM_BaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; //ʱÖÓ·Ö¸îΪ0   TIM_BaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;                 //TIMÏòÉϼÆÊýģʽ ´Ó0¿ªÊ¼ÏòÉϼÆÊý£¬¼ÆÊýµ½1000ºó²úÉú¸üÐÂʼþ   TIM_TimeBaseInit(TIM2, &TIM_BaseInitStructure); //¸ù¾ÝÖ¸¶¨²ÎÊý³õʼ»¯TIMʱ¼ä»ùÊý¼Ä´æÆ÷   TIM_ClearFlag(TIM2, TIM_FLAG_Update);//ÇåÖжϣ¬ÒÔÃâÒ»ÆôÓÃÖжϺóÁ¢¼´²úÉúÖÐ¶Ï   TIM_ARRPreloadConfig(TIM2, DISABLE);//½ûÖ¹ARR ԤװÔØ»º³åÆ÷   TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);//ʹÄÜTIM2ÖжÏÔ´   TIM_Cmd(TIM2, ENABLE);//TIM2×Ü¿ª¹Ø£º¿ªÆô      NVIC_InitTypeDef NVIC_InitStructure;   NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);   //ÉèÖÃÖжÏ×éΪ2   NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;   //ÖжÏʼþΪTIM2   NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;  //ÇÀÕ¼ÓÅÏȼ¶0     NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;      //ÏìÓ¦ÓÅÏȼ¶1   NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;         //ÔÊÐíÖÐ¶Ï   NVIC_Init(&NVIC_InitStructure);          }     void LEDXToggle(uint8_t ledx)   {         GPIOC->ODR^=GPIO_Pin_13;   }    void TIM2_IRQHandler(void)  {    static uint16_t count=0;   if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)   //ÅжÏÖжϱê־λÊÇ·ñΪ1£»Îª1ÔòÖжÏÏìÓ¦À²£¬0ÔòûÓÐ   {    TIM_ClearITPendingBit(TIM2, TIM_IT_Update);        //Çå³þÖжϹÒÆðλ    count++;    TIM_Count--;          //¶¨Ê±ÑÓʱ±äÁ¿¼õ1    if(count==500)          //¼ÆÊýµ½500ms    {     LEDXToggle(LED1);       //ÒÔ0.5ÃëµÃÖÜÆÚÉÁ˸     count=0;             //¼ÆÊýÇåÁã    }      }     }   void TIM2_delay(u16 time)   {    TIM_Count = time;    while(TIM_Count);   }         
转载请注明原文地址: https://www.6miu.com/read-2250063.html

最新回复(0)