当前位置:网站首页>Timer interrupt experiment based on stm32f103zet6 library function
Timer interrupt experiment based on stm32f103zet6 library function
2022-06-29 17:42:00 【It's Beichen bupiacra】
be based on STM32F103ZET6 Library function timer interrupt experiment
STM32F1 The timer is very powerful , Yes TIME1 and TIME8 Advanced timer, etc , Also have TIME2~TIME5 And so on , also TIME6 and TIME7 Wait for the basic timer .
We will use TIM3 Timer interrupt to control DS1 Flip of , Use... In the main function DS0 To indicate that the program is running .
STM32F1 General timer Introduction
STM32F1 The universal timer is a programmable prescaler (PSC) Driven 16 Bit auto loading counter (CNT) constitute .STM32 A universal timer can be used for : Measure the pulse length of the input signal ( Input capture ) Or produce Generate output waveform ( Output comparison and PWM) etc. . Use a timer prescaler and RCC Clock controller prescaler , Pulse length Degree and waveform period can be adjusted from a few microseconds to a few milliseconds .STM32 Each universal timer is completely independent , There are no resources shared with each other .
STM3F1 Common to TIMx (TIM2、TIM3、TIM4 and TIM5) Timer functions include :
1)16 Position up 、 Down 、 Up / Auto load counter down (TIMx_CNT).
2)16 Bit programmable ( It can be modified in real time ) Preassigned frequency counter (TIMx_PSC), The frequency division coefficient of the counter clock frequency is 1~ 65535 Any number between .
3)4 A separate channel (TIMx_CH1~4), These channels can be used as :
A. Input capture
B. Output comparison
C.PWM Generate ( Edge or center alignment mode )
D. Monopulse mode output
4) External signals can be used (TIMx_ETR) Control timer and timer Interconnection ( It can be used 1 A timer controls the other A timer ) The synchronous circuit of .
5) Interrupt occurs when the following events occur /DMA:
A. to update : The counter overflows up / Spilling down , Counter initialization ( Through software or internal / External trigger )
B. Triggering event ( The counter starts 、 stop it 、 Initialized or internally / External trigger count )
C. Input capture
D. Output comparison
E. Support for incremental positioning ( orthogonal ) Encoder and Hall sensor circuits
F. Trigger input as an external clock or current management by cycle
Timer related library functions mainly focus on firmware library files stm32f10x_tim.h and stm32f10x_tim.c In file
1.TIM3 Clock enable .
TIM3 It's mounted on APB1 under , So we went through APB1 The enable function under the bus enables TIM3. The function called is :
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); // Clock enable
2. Initialize timer parameters , Set auto reload value , Division coefficient , Counting method, etc .
In library functions , The initialization parameter of timer is through initialization function TIM_TimeBaseInit Realized :
voidTIM_TimeBaseInit(TIM_TypeDef*TIMx, TIM_TimeBaseInitTypeDef* TIM_TimeBaseInitStruct);
The first parameter is to determine which timer , This is easier to understand . The second parameter is the timer initialization parameter Structure pointer , The structural type is TIM_TimeBaseInitTypeDef
Let's take a look at the definition of this structure :
typedef struct
{
uint16_t TIM_Prescaler;
uint16_t TIM_CounterMode;
uint16_t TIM_Period;
uint16_t TIM_ClockDivision;
uint8_t TIM_RepetitionCounter;
} TIM_TimeBaseInitTypeDef;
This structure has 5 Member variables , It should be noted that , For general timers, only the first four parameters are useful , Last parameter TIM_RepetitionCounter It's the advanced timer that works .
The first parameter TIM_Prescaler It is used to set the frequency division coefficient .
The second parameter TIM_CounterMode Is used to set the counting mode , It was explained above that , It can be set to count up , Down counting and center aligned counting , More commonly used is the up count mode TIM_CounterMode_Up And to Next count mode TIM_CounterMode_Down.
The third parameter is to set the auto overload count cycle value .
The fourth parameter is used to set the clock division factor .
in the light of TIM3 Initialize sample code format :
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = 5000;
TIM_TimeBaseStructure.TIM_Prescaler =7199;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
3. Set up TIM3_DIER Allow update interrupt .
Because we need to use TIM3 The update of , The corresponding bit of the register enables the update interrupt . In the library function Timer interrupt enable is through TIM_ITConfig Function to implement :
void TIM_ITConfig(TIM_TypeDef* TIMx, uint16_t TIM_IT, FunctionalState NewState);
The first parameter is the timer , This is easy to understand , The value is TIM1~TIM17.
The second parameter is critical , Is used to indicate the type of timer interrupt that we enable , There are many types of timer interrupts Varied , Including update interrupt TIM_IT_Update, Trigger interrupt TIM_IT_Trigger, And input capture interrupt and so on .
The third parameter is very simple , Is it disabled or enabled .
For example, we need to enable TIM3 The update of , The format is :
TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE );
4.TIM3 Interrupt priority setting .
After timer interrupt enable , Because it's going to interrupt , It's essential to set up NVIC Related registers , Setting up Break priority . I have explained it many times before NVIC_Init Function to set the interrupt priority
5. allow TIM3 Work , That is to enable TIM3.
You can't just configure the timer , No timer on , Still can't use . We need to turn on the timer after configuration , adopt TIM3_CR1 Of CEN Bit to set . In the firmware library, the function to enable timer is through TIM_Cmd Function to implement :
void TIM_Cmd(TIM_TypeDef* TIMx, FunctionalState NewState);
Enable timer 3, Method is :
TIM_Cmd(TIM3, ENABLE); // Can make TIMx peripherals
6. Write interrupt service function .
In the firmware library function , The function used to read the value of interrupt status register and judge the type of interrupt is :
ITStatus TIM_GetITStatus(TIM_TypeDef* TIMx, uint16_t);
The function is to , Judge timer TIMx The interrupt type of TIM_IT Whether there is an interruption . such as , We must judge Chronometer 3 Whether there is an update ( overflow ) interrupt , Method is :
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)
{
}
The function of clearing interrupt flag bit in firmware library is :
void TIM_ClearITPendingBit(TIM_TypeDef* TIMx, uint16_t TIM_IT);
The function is to , Clear timer TIMx The interrupt TIM_IT Sign a . It's very simple to use , Let's say we have TIM3 After the overflow interrupt of , We want to clear the interrupt flag bit , The method is :
TIM_ClearITPendingBit(TIM3, TIM_IT_Update );
There's a little bit of clarification here , The firmware library also provides two functions to judge the timer status and clear the timer status flag The function of the sign TIM_GetFlagStatus and TIM_ClearFlag, Their role is similar to that of the previous two functions . only Is in TIM_GetITStatus The function will first determine whether the interrupt is enabled , Enable to judge the interrupt flag bit , and TIM_GetFlagStatus Directly used to determine the status flag bit .
Hardware design
The hardware resources used in this experiment are :
1) Indicator light DS0 and DS1
2) Timer TIM3
software design
timer.c
#include "timer.h"
#include "led.h"
// Universal timer 3 Interrupt initialization
// Here, the clock is selected as APB1 Of 2 times , and APB1 by 36M
//arr: Auto reload value .
//psc: Clock presplitting frequency
// Here's a timer 3
void TIM3_Int_Init(u16 arr,u16 psc)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); // Clock enable
// Timer TIM3 initialization
TIM_TimeBaseStructure.TIM_Period = arr; // Set the value of the auto reload register cycle for the next update event load activity
TIM_TimeBaseStructure.TIM_Prescaler =psc; // Set as TIMx Prescaled value of clock frequency divisor
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; // Set the clock split :TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM Upcount mode
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); // Initialize... According to the specified parameters TIMx Unit of time base
TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE ); // Enable to designate TIM3 interrupt , Allow update interrupt
// Interrupt priority NVIC Set up
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; //TIM3 interrupt
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; // Take precedence 0 level
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; // From the priority 3 level
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ The channel is energized
NVIC_Init(&NVIC_InitStructure); // initialization NVIC register
TIM_Cmd(TIM3, ENABLE); // Can make TIMx
}
// Timer 3 Interrupt service routine
void TIM3_IRQHandler(void) //TIM3 interrupt
{
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) // Check TIM3 Whether the update interrupt occurs or not
{
TIM_ClearITPendingBit(TIM3, TIM_IT_Update); // eliminate TIMx Update interrupt flag
LED1=!LED1;
}
}
System During initialization, the default system initialization function SystemInit The function has been initialized APB1 The clock is 2 frequency division , therefore APB1 The clock is 36M, And from STM32 The internal clock tree of : When APB1 The number of clock frequency division is 1 Of When ,TIM2~7 The clock is APB1 The clock of , And if the APB1 The number of clock divisions is not 1, that TIM2~7 When the The clock frequency will be APB1 Twice the clock . therefore ,TIM3 The clock is 72M, Then according to our design arr and psc Value , You can calculate the interruption time . The calculation formula is as follows :
Tout= ((arr+1)*(psc+1))/Tclk;
Tclk:TIM3 Input clock frequency ( Unit is Mhz).
Tout:TIM3 Overflow time ( Unit is us).
timer.h
#ifndef __TIMER_H
#define __TIMER_H
#include "sys.h"
void TIM3_Int_Init(u16 arr,u16 psc);
#endif
main.c
#include "led.h"
#include "delay.h"
#include "key.h"
#include "sys.h"
#include "usart.h"
#include "timer.h"
int main(void)
{
delay_init(); // Delay function initialization
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); // Set up NVIC Interrupt grouping 2:2 Bit preemption priority ,2 Bit response priority
uart_init(115200); // The serial port is initialized to 115200
LED_Init(); //LED Port initialization
TIM3_Int_Init(4999,7199); //10Khz The counting frequency of , Count to 5000 by 500ms
while(1)
{
LED0=!LED0;
delay_ms(200);
}
}
According to the formula above , We can calculate the interruption The overflow time is 500ms, namely Tout= ((4999+1)*( 7199+1))/72=500000us=500ms.
边栏推荐
- R language ggplot2 visualization: use the patchwork package (directly use the plus sign +) to horizontally combine the two ggplot2 visualization results, and then horizontally combine them with the th
- 基于gis三维可视化的智慧城市行业运用
- Walk with love, educate and run poor families, and promote public welfare undertakings
- L'intercepteur handlerinterceptor personnalisé permet l'authentification de l'utilisateur
- selenium上传文件
- 位图的详细介绍及模拟实现
- 正则表达式
- Digital twin energy system, creating a "perspective" in the low-carbon era
- ISO 32000-2 国际标准7.7
- 如何使用B/S开发工具DevExtreme的图表控件 - 自定义轴位置?
猜你喜欢

Does MySQL support foreign keys

Leetcode daily question - 535 Encryption and decryption of tinyurl

与爱同行,育润走进贫困家庭,助推公益事业

linux中mysql 1045错误如何解决

sequential detector

序列检测器

位图的详细介绍及模拟实现
![Fill in the next right node pointer of each node [make good use of each point - > reduce the space-time complexity as much as possible]](/img/33/bda0a898bfe3503197026d1f62e851.png)
Fill in the next right node pointer of each node [make good use of each point - > reduce the space-time complexity as much as possible]

育润多维发力慈善领域,勇抗企业公益大旗

Visio标注、批注位置
随机推荐
DevCloud加持下的青软,让教育“智”上云端
在线SQL转CSV工具
Visual studio plug-in coderush officially released v22.1 -- visual tool for optimizing debugging
使用 SSH 方式拉取代码
Mysql database literacy, do you really know what a database is
Opencv+YOLO-V3实现目标跟踪
Go语言多方式并发实现龟兔赛跑
两种Controller层接口鉴权方式
mac安装php7.2
How to use interrupt
Error:Connection refused: connect
R语言epiDisplay包的aggregate函数将数值变量基于因子变量拆分为不同的子集,计算每个子集的汇总统计信息、aggregate.data.frame函数包含缺失值的情况下分组统计结果为NA
Bags of Binary Words for Fast Place Recognition in Image Sequenc
面试中问最常问的海量数据处理你拿捏了没?
Walk with love, educate and run poor families, and promote public welfare undertakings
[webdriver] upload files using AutoIT
自定義HandlerInterceptor攔截器實現用戶鑒權
SCM系统是什么?供应链管理系统有哪些优势?
Redux源码分析之createStore
SRM供应商协同管理系统功能介绍