STM32的定時器輸入捕獲-超聲波測距案例
- gitee代碼
- 輸入捕獲硬件電路
- 案例說明
- 主函數代碼
gitee代碼
https://gitee.com/xiaolixi/l-stm32/tree/master/STM32F103C8T6/2-1tem-ld-timer-input-pluse
輸入捕獲硬件電路
超聲波測距
案例說明
- 使用超聲波測距傳感器
- 使用tim1的輸入捕獲測量超聲波傳感器的返回值,其中Echo引腳使用通道1和通道2的間接選擇,Trig使用PB0。距離小于1M點亮LED,LED燈使用PA1
主函數代碼
其他代碼見倉庫
#include "stm32f10x.h"
#include "LED.h"
#include "app_timer.h"
#include "Delay.h"
#include "math.h"#define TRIG GPIOB/**
Echo PA8
Trigger PB0
LED PA1
*/
void GPIOB_0_init() {// Trigger引腳RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);GPIO_InitTypeDef GPIO_InitStruct;GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0;GPIO_InitStruct.GPIO_Speed = GPIO_Speed_10MHz;GPIO_Init(TRIG, &GPIO_InitStruct);
}void timer_init(void) {RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);TIM_TimeBaseInitTypeDef TIM_TIM_TimeBaseInitStruct;TIM_TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;TIM_TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;TIM_TIM_TimeBaseInitStruct.TIM_Period = 65535;TIM_TIM_TimeBaseInitStruct.TIM_Prescaler = 71;TIM_TimeBaseInit(TIM1, &TIM_TIM_TimeBaseInitStruct);// Echo 引腳RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);GPIO_InitTypeDef GPIO_InitStruct;GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPD;GPIO_InitStruct.GPIO_Pin = GPIO_Pin_8;GPIO_Init(GPIOA, &GPIO_InitStruct);TIM_ICInitTypeDef TIM_ICInitStruct;TIM_ICInitStruct.TIM_Channel = TIM_Channel_1;TIM_ICInitStruct.TIM_ICFilter = 0;TIM_ICInitStruct.TIM_ICPolarity = TIM_ICPolarity_Rising;TIM_ICInitStruct.TIM_ICPrescaler = TIM_ICPSC_DIV1;TIM_ICInitStruct.TIM_ICSelection = TIM_ICSelection_DirectTI;TIM_ICInit(TIM1, &TIM_ICInitStruct);TIM_ICInitStruct.TIM_Channel = TIM_Channel_2;TIM_ICInitStruct.TIM_ICFilter = 0;TIM_ICInitStruct.TIM_ICPolarity = TIM_ICPolarity_Falling;TIM_ICInitStruct.TIM_ICPrescaler = TIM_ICPSC_DIV1;TIM_ICInitStruct.TIM_ICSelection = TIM_ICSelection_IndirectTI; // 間接選擇TIM_ICInit(TIM1, &TIM_ICInitStruct);
}int main(void)
{GPIOB_0_init();// LED 顯示LED_Init();LED1_OFF();timer_init();while(1) {TIM_SetCounter(TIM1, 0);TIM_ClearFlag(TIM1, TIM_FLAG_CC1);TIM_ClearFlag(TIM1, TIM_FLAG_CC2);TIM_Cmd(TIM1, ENABLE);GPIO_WriteBit(TRIG, GPIO_Pin_0, Bit_SET);Delay_us(20);GPIO_WriteBit(TRIG, GPIO_Pin_0, Bit_RESET);while(TIM_GetFlagStatus(TIM1, TIM_FLAG_CC1) == RESET) {;}while(TIM_GetFlagStatus(TIM1, TIM_FLAG_CC2) == RESET) {;}TIM_Cmd(TIM1, DISABLE);// 換算float distance = (TIM_GetCapture2(TIM1) - TIM_GetCapture1(TIM1)) * 1e-6 * 340.0f / 2;if (distance < 1.0) {LED1_ON();} else {LED1_OFF();}Delay_ms(100);}
}