写个程序示例,示例内容为stm32计数器如何输出当前计数值
时间: 2024-05-05 15:18:44 浏览: 43
Sure, here is an example program for STM32 counter to output its current count value:
```c
#include "stm32f4xx.h"
#include <stdio.h>
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
uint16_t count = TIM_GetCounter(TIM2);
printf("Current count value: %d\n", count);
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
}
int main(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitTypeDef timerInitStructure;
timerInitStructure.TIM_Prescaler = 0;
timerInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
timerInitStructure.TIM_Period = 65535;
timerInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM2, &timerInitStructure);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
NVIC_EnableIRQ(TIM2_IRQn);
TIM_Cmd(TIM2, ENABLE);
while(1)
{
}
}
```
This program initializes a TIM2 timer for counting. It then sets up an interrupt handler for the timer's update event. When the timer overflows and generates an update event, the interrupt handler reads the current count value and prints it to the console. The program then enters an infinite loop, waiting for the interrupt to occur.
Note that this is just a simple example program and it may need to be adapted to your specific use case.
阅读全文