STM32实现超声波测距

#include "stm32f10x.h"
#include "delay.h"
#include "sys.h"
#include "usart.h"
int tim,len;
void Init(){
	GPIO_InitTypeDef GPIO_InitStructer;
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructer;

	RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOB, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

	GPIO_InitStructer.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_InitStructer.GPIO_Mode=GPIO_Mode_Out_PP;
	GPIO_InitStructer.GPIO_Pin=GPIO_Pin_8;
	GPIO_Init(GPIOB, &GPIO_InitStructer);

	GPIO_InitStructer.GPIO_Mode=GPIO_Mode_IN_FLOATING;
	GPIO_InitStructer.GPIO_Pin=GPIO_Pin_9;
	GPIO_Init(GPIOB, &GPIO_InitStructer);
	
	TIM_DeInit(TIM2);
	TIM_TimeBaseInitStructer.TIM_Period=999;
	TIM_TimeBaseInitStructer.TIM_Prescaler=71;
	TIM_TimeBaseInitStructer.TIM_ClockDivision=TIM_CKD_DIV1;
	TIM_TimeBaseInitStructer.TIM_CounterMode=TIM_CounterMode_Up;
	TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructer);
	TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
	TIM_Cmd(TIM2,DISABLE);

}

int main(){
	uart_init(115200);
	delay_init();	
	Init();
	while(1){
		delay_ms(10000);	
		PBout(8)=1; 
		delay_us(20); 
		PBout(8)=0;
		while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_9)==RESET);
		TIM_Cmd(TIM2,ENABLE);
		while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_9)==SET);
		TIM_Cmd(TIM2,DISABLE);
		tim=TIM_GetCounter(TIM2);
		len=tim*34/2000; 
		TIM2->CNT=0;
		printf("Present Length is : %d cm\n", len);	
	}
}

发布了70 篇原创文章 · 获赞 22 · 访问量 6480

猜你喜欢

转载自blog.csdn.net/weixin_44410512/article/details/103410322