使用c语言编写基于STM32F103ZET6芯片PE2和PE3按键控制TIM2定时器的周期值增大和减小
时间: 2023-06-25 15:04:27 浏览: 55
好的,以下是基于STM32F103ZET6芯片的PE2和PE3按键控制TIM2定时器周期值增大和减小的C代码示例:
```
#include "stm32f10x.h"
void TIM2_Configuration(void);
void GPIO_Configuration(void);
int main(void)
{
GPIO_Configuration();
TIM2_Configuration();
while(1)
{
if(GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_2) == RESET) // PE2按键被按下
{
TIM2->ARR++; // 增加TIM2的周期值
while(GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_2) == RESET); // 等待按键释放
}
if(GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_3) == RESET) // PE3按键被按下
{
TIM2->ARR--; // 减小TIM2的周期值
while(GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_3) == RESET); // 等待按键释放
}
}
}
void TIM2_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); // 使能TIM2时钟
TIM_TimeBaseStructure.TIM_Period = 999; // 定时器周期为1000
TIM_TimeBaseStructure.TIM_Prescaler = 71; // 定时器预分频器为72
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; // 不分频
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; // 向上计数模式
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); // 初始化TIM2
TIM_Cmd(TIM2, ENABLE); // 使能TIM2
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE); // 使能GPIOE时钟
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3; // PE2和PE3引脚
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; // 设置为上拉输入模式
GPIO_Init(GPIOE, &GPIO_InitStructure); // 初始化GPIOE
}
```
在以上代码中,我们使用了STM32F10x标准库函数来进行TIM2和GPIO的初始化配置。其中,TIM2的周期值默认为999,预分频器为71,所以定时器的周期为1000。按下PE2按键可以增加TIM2的周期值,相当于减小定时器的频率,使得定时器中断的时间间隔增大;按下PE3按键可以减小TIM2的周期值,相当于增加定时器的频率,使得定时器中断的时间间隔减小。注意,在修改周期值后需要等待一段时间,直到定时器的计数器重新计数才能看到效果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)