Advertisement
Domy131097

[LV5] Mikroračunalni sustavi - timeri

Apr 21st, 2018
128
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*====================== TIMERI ======================*/
  2.  
  3. /* Includes */
  4. #include <stddef.h>
  5. #include "stm32f10x.h"
  6. #include "stm32f10x_rcc.h"
  7. #include "stm32f10x_gpio.h"
  8. #include "stm32f10x_tim.h"
  9.  
  10. volatile uint32_t millis;
  11.  
  12. void initGPIO(void);
  13. void initTimer(void);
  14. void SysTick_Handler(void);
  15. void wait(uint32_t time);
  16.  
  17. int main(void) {
  18.     uint32_t intenzity = 0;
  19.  
  20.     //inizijalizacija
  21.     initGPIO();
  22.     initTimer();
  23.  
  24.     SysTick_Config(SystemCoreClock / 1000); // 1 ms
  25.     //ciklicko ponavljanje
  26.     while(1){
  27.         TIM_SetCompare2(TIM2, intenzity);
  28.         TIM_SetCompare3(TIM2, 1000 - intenzity);
  29.         intenzity += 100;
  30.         if(intenzity > 1000) intenzity = 0;
  31.         wait(100);
  32.     }
  33. }
  34.  
  35. void initGPIO(void) {
  36.     GPIO_InitTypeDef GPIO_InitStruct;
  37.  
  38.     RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
  39.  
  40.     GPIO_StructInit(&GPIO_InitStruct);
  41.     GPIO_InitStruct.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2;
  42.     GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
  43.     GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
  44.     GPIO_WriteBit(GPIOA, GPIO_Pin_1, Bit_RESET);
  45.     GPIO_Init(GPIOA, &GPIO_InitStruct);
  46. }
  47.  
  48. void initTimer(void) {
  49.     TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
  50.     TIM_OCInitTypeDef TIM_OCInitStruct;
  51.  
  52.     RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
  53.  
  54.     //inicijalizacija timera
  55.     TIM_TimeBaseStructInit(&TIM_TimeBaseInitStruct);
  56.     TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
  57.     TIM_TimeBaseInitStruct.TIM_Period = 1000 - 1;
  58.     TIM_TimeBaseInitStruct.TIM_Prescaler = SystemCoreClock / 100000 - 1; //100kHz
  59.     TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1; //null
  60.     TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0; //null
  61.     TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruct);
  62.  
  63.     //inicijalizacija PWM
  64.     TIM_OCStructInit(&TIM_OCInitStruct);
  65.     TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
  66.     TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
  67.     TIM_OC2Init(TIM2, &TIM_OCInitStruct);
  68.     TIM_OC3Init(TIM2, &TIM_OCInitStruct);
  69.  
  70.     TIM_Cmd(TIM2, ENABLE);
  71. }
  72.  
  73. void wait(uint32_t time) {
  74.     millis = time;
  75.     while(millis > 0);
  76. }
  77.  
  78. void SysTick_Handler(void) {
  79.     if(millis > 0) {
  80.         millis--;
  81.     }
  82. }
Advertisement
RAW Paste Data Copied
Advertisement