STM32 定时器控制微秒延时

Dara ·
更新时间:2024-11-13
· 851 次阅读

定时器控制微秒延时

void MX_TIM3_Init(void) { TIM_SlaveConfigTypeDef sSlaveConfig = {0}; TIM_MasterConfigTypeDef sMasterConfig = {0}; htim3.Instance = TIM3; htim3.Init.Prescaler = 16-1; htim3.Init.CounterMode = TIM_COUNTERMODE_UP; htim3.Init.Period = 10000; htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; if (HAL_TIM_Base_Init(&htim3) != HAL_OK) { Error_Handler(); } sSlaveConfig.SlaveMode = TIM_SLAVEMODE_DISABLE; sSlaveConfig.InputTrigger = TIM_TS_ITR0; if (HAL_TIM_SlaveConfigSynchro(&htim3, &sSlaveConfig) != HAL_OK) { Error_Handler(); } sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK) { Error_Handler(); } }

主程序

//main.c extern uint64_t microTick; //初始化 if (HAL_TIM_Base_Start_IT(&htim3) != HAL_OK) { Error_Handler(); } uint64_t getMicroSeconds() { return microTick + (htim3.Instance->CNT); } void delayMicroseconds(uint32_t micros) { uint64_t tickStart = getMicroSeconds(); while ((getMicroSeconds() - tickStart) < micros) { } } int main(void) { while (1) { led_on(); delayMicroseconds(1000000); led_off(); delayMicroseconds(1000000); } } //stm32f0xx_it.c extern TIM_HandleTypeDef htim3; volatile uint64_t microTick = 0; void TIM3_IRQHandler(void) { HAL_TIM_IRQHandler(&htim3); microTick += 10000; } kay_2017 原创文章 45获赞 16访问量 3万+ 关注 私信 展开阅读全文
作者:kay_2017



定时器 stm32

需要 登录 后方可回复, 如果你还没有账号请 注册新账号