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);
}
}