写一段用STM32计时的代码
时间: 2023-12-17 19:49:48 浏览: 27
Sure, here is some code for you:
```
#include "stm32f4xx_hal.h"
#include "stm32f4xx_hal_tim.h"
// Initialize timer
TIM_HandleTypeDef htim;
void TIM_Init(void) {
TIM_MasterConfigTypeDef sMasterConfig;
// Enable timer clock
__HAL_RCC_TIM2_CLK_ENABLE();
// Set timer base parameters
htim.Instance = TIM2;
htim.Init.Prescaler = 84 - 1;
htim.Init.CounterMode = TIM_COUNTERMODE_UP;
htim.Init.Period = 999;
htim.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
HAL_TIM_Base_Init(&htim);
// Set timer to update its counter every 1ms
HAL_TIM_Base_Start_IT(&htim);
// Configure timer interrupt
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
HAL_TIMEx_MasterConfigSynchronization(&htim, &sMasterConfig);
}
// Timer interrupt handler
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
static uint32_t counter = 0; // Local counter variable
// Increment counter every 1ms
counter++;
// Do something every second
if (counter == 1000) {
// Your code here
counter = 0;
}
}
int main(void) {
// Initialize timer
TIM_Init();
// Your code here
return 0;
}
```
This code initializes a timer on the STM32 microcontroller to generate an interrupt every 1ms. You can do whatever you want in the interrupt handler, but in this example, it increments a counter variable every 1ms and performs some action every second. Note that this is just a simple example and you may need to modify the code to suit your specific requirements.