Timer

Pages List
List view
Home
Portfolio
HW
FW
SW
FPGA / Adaptive SoC
Daily
Photo
Etc
 
STM32 Peripheral

Timer


notion image

Timer에 대한 기본적인 설명


notion image
 
notion image
 
notion image
Count값이 설정한 최대값에서 0으로 다시 돌아올 때, Update event가 발생한다.
Update event는 Timer Interrupt를 발생시키는데 사용할 수 있다.
 
 

Timer의 종류와 기능


notion image
STM32의 Timer에는 3가지 종류가 있다.
Basic Timer는 모든 STM32 MCU에 최소 1개씩 존재한다.
General Purpose Timer는 대부분의 STM32 MCU가 갖지만 몇몇은 그렇지 않다.
(PPT에 잘못 설명되어 있다. Datasheet를 참조해야 함.)
Advanced Timer는 갖고 있는 MCU도 있고, 그렇지 않은 MCU도 있어서 마찬가지로 Datasheet를 참조해야 한다.
 
다음은 STM32F407가 갖고 있는 Timer의 목록과 기능을 정리한 표이다.
notion image
notion image
 
notion image
 
 

Basic Timer에 대한 설명


notion image
Basic TImer는 기본적인 Counting 기능만 가지고 있고 Time base generation에 주로 사용된다.
그리고 Basic Timer는 입력 채널과 출력 채널을 갖지 않는다.
 
notion image
CNT 값이 증가하거나 감소해서 User가 사전에 설정한 ARR 레지스터의 값에 도달하면, CNT 값은 초기화되고 Update Event가 발생한다. 그리고 Update Event는 Processor의 Interrupt 발생 요인으로 사용할 수 있다.
 
다음은 Timer base unit에 대한 설명이다.
notion image
Time base unit은 위의 그림에서 CNT counter, PSC prescaler, ARR 레지스터를 총칭한다.
 
 

Timer Handle Structure


notion image
Timer Peripheral도 UART Peripheral처럼 Handle Structure가 필요하다.
 
다음은 Timer Handle Structure의 멤버들이다.
notion image
 
Timer의 Time base unit은 TIM_Base_InitTypeDef의 Structure에서 설정한다.
notion image
 
다음은 TIM_Base_InitTypeDef의 멤버들이다.
notion image
 
notion image
 
다음 그림은 STM32F407의 Clock Tree의 APB1 Timer Clock 부분이다.
notion image
Timer6는 APB1으로부터 Clock을 공급받는다.
만약 APB1 prescaler값이 1이면, APB1 Clock Speed가 그대로 Timer의 Clock Speed가 된다.
그러나 APB1 prescaler값이 1이 아니면, Timer에 공급되는 Clock speed는 APB1 Clock의 2배가 된다.
 
 

Timer의 Time base unit에 대해 알아보자


① Prescaler

notion image
Prescaler는 Timer Clock을 prescale해서 어떤 속도로 Count를 할 것인지를 결정한다.
 
다음은 Prescaler값에 따른 Count 속도의 변화를 보여준다.
notion image
 
notion image
 
notion image
 

② Period

notion image
Timer의 Count값이 증가하거나 감소하다가 ARR값에 도달하면, 초기값으로 돌아가는 동시에 Update Event를 발생시킨다.
ARR(Auto-Reload Register)의 설정값에 따라 Update Event의 발생 주기를 결정할 수 있다.
( ARR값이 0이면 Timer는 동작하지 않는다. )
 
 

Period (ARR값) 계산하는 방법


notion image
100ms의 Time base를 얻기 위해서는 Timer Clock을 24로 분주하고 ARR값을 64000으로 설정해야 한다.
Timer Clock을 분주하지 않고 그대로 사용하면, 16bit – ARR 레지스터가 가질 수 있는 최대값인 65535을 초과하기 때문에 불가능하다.
 
사실, 정확하게 말하면 ARR레지스터에 넣어야 하는 값은 64000이 아니라 63999이다.
notion image
notion image
위 그림처럼 1MHz의 Count Clock을 사용해서 5us의 Time base를 만드려고 할 때, 사람들은 보통 ARR 레지스터에 5를 넣으면 된다고 착각한다.
하지만 Count값이 다시 초기값으로 돌아가고 Update Event가 발생하는 시점은 Count값이 ARR계산값에 도달하는 순간이 아니라, “ARR계산값+1″에 도달하는 순간이다.
그래서 결과적으로는 6us의 Time base가 만들어지기 때문에, “ARR계산값-1″을 ARR 레지스터에 넣는 것이 5us의 Time base를 얻을 수 있는 바람직한 방법이다.
 
역으로 Update Event의 발생 빈도는 다음과 같이 구할 수 있다.
notion image
여기서 ARR은 실제 ARR 레지스터에 들어가는 값을 말하고, “ARR+1″은 ARR계산값으로 보면 된다.
 
다음은 Time-Base Unit에 대한 내용을 정리한 것이다.
notion image
 
 

100ms의 Time Base를 만드는 예제 (by Polling mode)


notion image
notion image
 
 

100ms의 Time Base를 만드는 예제 (by Interrupt mode)


notion image
notion image
 
UART의 경우와 같이, TIM6 IRQ Handler에서는 Interrupt Processing API인 “HAL_TIM_IRQHandler”만 호출하면 된다.
notion image
 
 

10us의 Time Base를 만드는 예제 (by using PLL & Interrupt mode)


notion image
notion image
notion image
notion image
notion image
 
notion image
 
 

General Purpose Timer : Input Capture Unit


notion image
Basic Timer는 외부 신호를 입력받을 수 없기 때문에 입력신호를 Capture할 수 없다.
그래서 이 경우에는 Input Capture Unit을 가진 General Purpose Timer를 사용해야 한다.
 
General Purpose Timer는 Basic Timer의 기능(Time Base Unit) 또한 포함하고 있다.
Timer의 channel은 Capture와 Compare의 기능을 모두 가지므로 둘 중 하나를 선택해서 사용한다.
(Capture channel, Compare channel 각각 4개씩 해서 8개가 아니다. Timer의 channel은 그냥 4개다.)
 
다음은 General Purpose Timer의 Input Capture block을 간략하게 표현한 그림이다.
notion image
 
이제 Input Capture block이 동작하는 원리를 살펴보자.
notion image
  1. 입력신호의 Rising Edge가 검출되면, 그 때의 Timer Counter값이 Capture/Compare 레지스터에 저장되고, User는 이 값을 따로 저장해 둔다. (Capture Interrupt 발생시 Callback 함수에서 수행)
  1. 입력신호의 다음 Rising Edge가 검출되면, 다시 그 때의 Timer Counter값이 Capture/Compare 레지스터에 저장되고, User는 이 값을 따로 저장해 둔다. (Capture Interrupt 발생시 Callback 함수에서 수행)
  1. 두 Timer Counter값의 차이가 입력신호의 주기이고, 역수를 취한 값이 입력신호의 주파수가 된다.
 
Timer Input Capture를 사용하기 위해서는 다음과 같이 2가지의 절차를 수행해야 한다.
notion image
 
① HAL_TIM_IC_Init API를 실행해서 Timer Input Capture Time base를 Initialize한다.
notion image
 
② HAL_TIM_IC_ConfigChannel API를 실행해서 Timer의 Input Channel을 Configuration한다.
notion image
 
notion image
 
 

LSE 주파수 32.768kHz를 Input Capture로 측정하는 예제


notion image
notion image
notion image
notion image
notion image
notion image
notion image
notion image
 

[ 실행 결과 ]

notion image
 
notion image
 
LSE 대신에 HSI나 HSE 등을 입력해보면, UART로 Frequency가 출력되지 않는다.
이는 해당 주파수가 너무 높아서, TIM2의 Interrupt Handler의 Interrupt Processing API를 수행 완료하기 전에 다음 Interrupt가 들어오기 때문이다.
(Interrupt Handler만 계속 실행되어, main함수에서 Frequency 계산과 UART 송신이 불가능하다.)
 
 

Timer’s Output Compare Unit


notion image
 
notion image
이번에는 Timer의 Output Compare 모드에 알아보고, 위와 같은 예제를 직접 수행해본다.
 
Timer의 Output Compare 모드는 어떻게 동작하는지 알아보자.
notion image
Output Compare 모드는 다음과 같은 방식으로 Waveform을 생성한다.
CCR1 레지스터에 값(Pulse)을 저장하고 Timer를 동작시키면, Timer count값이 CCR1값과 같아질 때마다 Output channel이 toggle된다.
그리고 새로운 값을 CCR1 레지스터에 저장하면, 다시 Timer count값이 CCR1값과 같아질 때마다 Output channel이 toggle된다. (값이 match될 때마다 Interrupt가 발생하므로 Callback 함수에서 새로운 CCR1값을 쓰면 된다.)
 
notion image
 

① HAL_TIM_OC_Init API를 실행해서 Timer Output Compare Time base를 Initialize한다.

notion image
 

② HAL_TIM_OC_ConfigChannel API를 실행해서 Timer의 Output Channel을 Configuration한다.

1. Output Compare mode는 Toggle로 설정한다.

notion image
Timer count값이 CCR1 레지스터값과 같아질 때, Output Channel이 Toggle되는 것을 볼 수 있다.
현재 CCR1값과 이전 CCR1값의 차이를 Pulse라고 한다. ( = Output channel의 pulse 폭)
 

2. Output Compare Polarity는 OCPolarity High로 설정한다. (반전되지 않고, 그대로 출력)

notion image
OCPolarity가 High일 때는 OC1ref가 그대로 출력되고, Low일 때는 반전되서 출력된다.
 

3. Output Compare Pulse는 500Hz에 대응하는 Pulse값으로 설정한다.

notion image
Timer Count Clock이 25MHz일 때, Output Channel1으로 500Hz의 Waveform을 만드려고 한다.
주파수 500Hz인 신호의 주기는 0.002sec이므로, Pulse는 0.001sec이다.
25MHz의 Timer Count Clock으로 count하면, 0.001sec는 25000에 대응된다.
 
 

Timer Output Compare로 500Hz, 1000Hz, 2000Hz, 4000Hz 파형 만드는 예제


notion image
notion image
notion image
notion image
notion image
notion image
notion image
notion image
 
notion image
 
 

PWM


notion image
PWM mode에서 출력 신호의 Duty Cycle을 가변해서, 평균전압을 바꿀 수 있다.
 
notion image
PWM mode에서 ‘TIM_OC_InitTypeDef’ 구조체의 Pulse 값은 (Period * Duty Cycle)로 계산할 수 있다.
Timer의 Update Event가 1ms마다 발생하고 이에 해당하는 ARR값이 10000일 때, 40% Duty Cycle에 알맞은 Pulse값은 (10000 * 40/100) = 4000이다.
Active State는 Count값이 CCR값과 match 하기전의 PWM 출력을 말하고 InActive State는 match 한 후를 말하는데, ‘TIM_OC_InitTypeDef’ 구조체의 OCPolarity가 High이면 Active state에서 High이고, InActive state에서 Low이다. (.OCPolarity가 Low이면, 반대가 된다.)
 
notion image
 
notion image
PWM에서는 Update Event가 발생할 때, Update할게 없으므로 Callback함수를 호출하지 않는다.
(도중에 Duty Cycle을 변경하지 않는 이상, 처음에 입력한 Duty Cycle에 대응하는 Pulse값을 그대로 사용한다.)
 
 

PWM으로 25%, 45%, 75%, 90% Duty Cycle의 출력 신호를 만드는 예제


notion image
notion image
notion image
notion image
notion image
notion image
 
TIM_OC_InitTypeDef 구조체의 OCMode에서 ‘TIM_OCMODE_PWM1’를 ‘TIM_OCMODE_PWM2’로 바꾸면, PWM 출력 신호가 반전되서 출력된다.
notion image
notion image