phillip_bourdon234

delay.c

Feb 28th, 2021 (edited)
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.42 KB | None | 0 0
  1. #include "stm32f10x.h"
  2. #include "delay.h"
  3.  
  4. volatile static int ticks_delay = 0;
  5. volatile static int ticks_millis = 0;
  6. volatile static uint8_t millis_flag = 0;
  7. volatile static uint8_t delay_flag = 0;
  8.  
  9. int start_millis(void)
  10. {
  11.     millis_flag = 1;
  12.     TIM2->CR1 |= TIM_CR1_CEN; //turn timer on
  13.    
  14.     return ticks_millis;
  15. }
  16.  
  17. void reset_millis(void)
  18. {
  19.     millis_flag = 0;
  20.     TIM2->CR1 &= ~(TIM_CR1_CEN);
  21.     ticks_millis = 0;
  22. }
  23.  
  24. int play_millis(int time)
  25. {
  26.     millis_flag = 1;
  27.     TIM2->CR1 |= TIM_CR1_CEN; //turn timer on
  28.    
  29.     if(ticks_millis > time)
  30.     {
  31.         reset_millis();
  32.     }
  33.    
  34.     return ticks_millis;
  35. }
  36.  
  37.  
  38. void init_delay(void)
  39. {
  40.     RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;
  41.    
  42.     TIM2->PSC = 0;
  43.     TIM2->ARR = 72; // 1Mhz for easy timing with uS and mS
  44.    
  45.     TIM2->CR1 |= TIM_CR1_URS;
  46.     TIM2->DIER |= TIM_DIER_UIE;
  47.     TIM2->EGR |= TIM_EGR_UG;
  48.    
  49.     NVIC_EnableIRQ(TIM2_IRQn);
  50. }
  51.  
  52. void TIM2_IRQHandler()
  53. {
  54.     TIM2->SR &= ~TIM_SR_UIF;
  55.     if(delay_flag)
  56.     {
  57.         ticks_delay++;
  58.     }
  59.     if(millis_flag)
  60.     {
  61.         ticks_millis++;
  62.     }
  63. }
  64.  
  65.  
  66. void delayUs(int uS)
  67. {
  68.     ticks_delay = 0;
  69.     delay_flag = 1;
  70.     TIM2->CR1 |= TIM_CR1_CEN; //turn timer on
  71.  
  72.     while(ticks_delay < uS){}
  73.    
  74.     TIM2->CR1 &= ~TIM_CR1_CEN; //turn timer off
  75.     delay_flag = 0;
  76. }
  77.  
  78. void delayMs(int mS)
  79. {
  80.     ticks_delay = 0;
  81.     delay_flag = 1;
  82.     TIM2->CR1 |= TIM_CR1_CEN; //turn timer on
  83.  
  84.     while(ticks_delay < (mS * 1000)){}
  85.  
  86.     TIM2->CR1 &= ~TIM_CR1_CEN; //turn timer off
  87.     delay_flag = 0;
  88. }
  89.  
Add Comment
Please, Sign In to add comment