I am going to use the laser ranging module and need to count microseconds. I use timer 4 and set the time to 1um. I add 1 to the variable every time it is interrupted. When testing, I first clear the variable in the main loop, then start timer 4, stop timer 4 later, and then display the variable value. The code is generated by CubeMX, STM32F103C8T6 chip, the program is compiled and can be run, but the variable value will not change. It may be that timer 4 did not start normally, or it may be caused by incorrect configuration. The relevant code is as follows. Please help me find out what the problem is. Thank you in advance!
1. tim.c file
#include "tim.h"
extern uint16_t distance;
TIM_HandleTypeDef htim4;
void MX_TIM4_Init(void)
{
TIM_SlaveConfigTypeDef sSlaveConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
htim4.Instance = TIM4;
htim4.Init.Prescaler = (72-1);
htim4.Init.CounterMode = TIM_COUNTERMODE_UP;
htim4.Init.Period = (1000-1);
htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim4.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
if (HAL_TIM_Base_Init(&htim4) != HAL_OK)
{
Error_Handler();
}
sSlaveConfig.SlaveMode = TIM_SLAVEMODE_RESET;
sSlaveConfig.InputTrigger = TIM_TS_ITR0;
if (HAL_TIM_SlaveConfigSynchronization(&htim4, &sSlaveConfig) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim4, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
_HAL_TIM_Base_MspInit(&htim4);
}
void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* tim_baseHandle)
{
if(tim_baseHandle->Instance==TIM4)
{
__HAL_RCC_TIM4_CLK_ENABLE();
HAL_NVIC_SetPriority(TIM4_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(TIM4_IRQn);
}
}
2. tim.h file
#ifndef __tim_H
#define __tim_H
#ifdef __cplusplus
extern "C" {
#endif
#include "main.h"
extern TIM_HandleTypeDef htim4;
void MX_TIM4_Init(void);
#ifdef __cplusplus
}
#endif
#endif /*__ tim_H */
3. stm321xx_it.c file (part)
void TIM4_IRQHandler(void)
{
/* USER CODE BEGIN TIM4_IRQn 0 */
/* USER CODE END TIM4_IRQn 0 */
HAL_TIM_IRQHandler(&htim4);
/* USER CODE BEGIN TIM4_IRQn 1 */
distance++;
/* USER CODE END TIM4_IRQn 1 */
}
4. Operation of timer in main.c file
int main(void)
{
uint8_t i;
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_RTC_Init();
MX_TIM4_Init();
MX_ADC1_Init();
MX_I2C1_Init();
MX_SPI1_Init();
MX_USART1_UART_Init();
LCD_init();
display_main();
led_green_off();
while (1)
{
distance = 0; //清零计数值
HAL_TIM_Base_Start(&htim4); //开启定时器
if(keyf>0){
LCD_write_value(10,1,3,0,1,keyf);
LCD_write_value(10,2,3,0,1,keys);
}
if(ms>999){
ms = 0;
led_green_flashing();
led_red_flashing();
}
HAL_TIM_Base_Stop(&htim4); //关闭定时器
LCD_write_value(10,3,5,0,1,distance); //显示定时器中断次数(计时)
}
}
|