留意:界说GPIOB2为超声输出;GPIOB10为输入,定时器用TIm2
#include “HCSR04.h”
#include “delay.h”
#include “sys.h”
int overcount;
float length=0;
void HCSR04_init()
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TImeBaseInitTypeDef TIM_TimeBaseInitStructer;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB , ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
TIM_DeInit(TIM2);
TIM_TimeBaseInitStructer.TIM_Period=4999;
TIM_TimeBaseInitStructer.TIM_Prescaler=7199;
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_ITConfig(
TIM2,
TIM_IT_Update |
TIM_IT_Trigger,
ENABLE
);
TIM_ClearFlag(TIM2,TIM_FLAG_Update);
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQChannel;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIM2,DISABLE);
}
float HCSR04_Read()
{
float sum=0,length1=0;
u8 i=0,j=0;
u16 tim;
{
// while(i!=5)
for(i=0;i《5;i++)
{
PBout(2)=1;
delay_us(20);
PBout(2)=0;
while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_10)==RESET);
TIM_SetCounter(TIM2,0);
TIM_Cmd(TIM2,ENABLE);
while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_10)==SET);
TIM_Cmd(TIM2,DISABLE);
tim=TIM2-》CNT;
length1=tim/58.0*100;
TIM2-》CNT=0;
sum+=length1;
}
}
length=sum/5;
sum=0;
return length;
}
///////////////////////////////////////////////////.h文件//////////////////////////////////////////////////////////////////
#include “stm32f10x_lib.h”
#define PBout(n) BIT_ADDR(GPIOB_ODR_Addr,n) //ê?3?
#define PBin(n) BIT_ADDR(GPIOB_IDR_Addr,n) //ê?è?
extern float HCSR04_Read();
extern void HCSR04_init();
//extern void HC_RS04_Init();