简单超声波测距

用到模块 hc-sr04超声波模块,stm32开发板

本实验通过超声波测距模块得到长度 直接打印到窗口显示,故主要用到定时器函数,串口函数

hcsr04.c

/* 
只需要提供一个 10uS以上脉冲触发信号,该模块内部将
发出8个 40kHz周期电平并检测回波。一旦检测到有回波信号则输出回响信号。
回响信号的脉冲宽度与所测的距离成正比。 由此通过发射信号到收到的回响信号
时间间隔可以计算得到距离。 公式: uS/58=厘米或者uS/148=英寸; 或是: 距离=
高电平时间*声速( 340M/S) /2; 建议测量周期为 60ms以上, 以防止发射信号对
回响信号的影响
测量距离2cm-400cm 精度3mm
*/

#include "hcsr04.h" 
#define HCSR04_PORT     GPIOB
#define HCSR04_CLK      RCC_APB2Periph_GPIOB
#define HCSR04_TRIG     GPIO_Pin_5
#define HCSR04_ECHO     GPIO_Pin_6 
#define TRIG_Send  PBout(5) 
#define ECHO_Reci  PBin(6) 
u16 msHcCount = 0;
	void Hcsr04Init()
{      
			TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;     //定时器的结构体
			GPIO_InitTypeDef GPIO_InitStructure;    						//GPIOB结构体初始化
			RCC_APB2PeriphClockCmd(HCSR04_CLK, ENABLE);            
	
			GPIO_InitStructure.GPIO_Pin =HCSR04_TRIG;       //Trig引脚  
			GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;    
			GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;//输出模式  
			GPIO_Init(HCSR04_PORT, &GPIO_InitStructure);    
	
			GPIO_ResetBits(HCSR04_PORT,HCSR04_TRIG);        //拉低,为后面准备
	
			GPIO_InitStructure.GPIO_Pin =   HCSR04_ECHO;     //Echo引脚 
			GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//输入模式    
			GPIO_Init(HCSR04_PORT, &GPIO_InitStructure);  		
	
			GPIO_ResetBits(HCSR04_PORT,HCSR04_ECHO);		 			//拉低	
	
			TIM_DeInit(TIM6);																	//定时器初始化结构体
			
			RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6, ENABLE);   
			TIM_TimeBaseStructure.TIM_Period = (1000-1); //预装载值
			TIM_TimeBaseStructure.TIM_Prescaler =(72-1); //分频系数	
			TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;//不分频	
			TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  //向上计数		
			TIM_TimeBaseInit(TIM6, &TIM_TimeBaseStructure); 
			
			TIM_ClearFlag(TIM6, TIM_FLAG_Update);   //清除更新中断		
			TIM_ITConfig(TIM6,TIM_IT_Update,ENABLE);    //打开更新中断		
			hcsr04_NVIC();    
			TIM_Cmd(TIM6,DISABLE);     
	}  
			static void OpenTimerForHc()        //打开定时器
			{        
			TIM_SetCounter(TIM6,0);							//清除计数        
			msHcCount = 0;        
			TIM_Cmd(TIM6, ENABLE);  						//使能定时器
			} 
			static void CloseTimerForHc()        //关闭定时器
			{        
			TIM_Cmd(TIM6, DISABLE); 
			}   
			
		 void hcsr04_NVIC()                    //中断优先级管理
			{			
			NVIC_InitTypeDef NVIC_InitStructure;			
			NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);			
				
			NVIC_InitStructure.NVIC_IRQChannel = TIM6_IRQn;             	
			NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;  		
			NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;         	
			NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;        	
			NVIC_Init(&NVIC_InitStructure);
			}  
			
			void TIM6_IRQHandler(void)   //中断服务函数
			{        
			if (TIM_GetITStatus(TIM6, TIM_IT_Update) != RESET)  //检测更新中断是否发生     
			{                
			TIM_ClearITPendingBit(TIM6, TIM_IT_Update  );  //发生则清除标志位                
			msHcCount++;       																//计数值加1
			}

			} 
			
			u32 GetEchoTimer(void)                     //定时器时间获取
			{        
			u32 t = 0;        
			t = msHcCount*1000;      
			t += TIM_GetCounter(TIM6);//得到us	      
			TIM6->CNT = 0;  //将TIM6的计数值清零				
			delay_ms(50);    //消除余震    
			return t;
				
			} 
			
			
			
			//多次测量求平均
			float Hcsr04GetLength(void)
			{		
			u32 t = 0;		
			int i = 0;		
			float lengthTemp = 0;		
			float sum = 0;		
			while(i!=5)		
			{		
			TRIG_Send = 1;      //发送高电平
			delay_us(20);		    //延时20us
			TRIG_Send = 0;			//拉低
			while(ECHO_Reci == 0);      //等待接收高电平Echo
			OpenTimerForHc();        //打开定时器			
			i = i + 1;			
			while(ECHO_Reci == 1);			//接收Echo
			CloseTimerForHc();        //接受完成关闭定时器		
			t = GetEchoTimer();        //获取时间,单位us		
			lengthTemp = ((float)t/58.0);//获得长度,单位cm			
			sum = lengthTemp + sum ;			
			}		
			lengthTemp = sum/5.0;		     //多次测量的平均值
			return lengthTemp;
		}

usart.c

#include "sys.h"
#include "usart.h"	  
////////////////////////////////////////////////////////////////////////////////// 	 
//如果使用ucos,则包括下面的头文件即可.
#if SYSTEM_SUPPORT_OS
#include "includes.h"					//ucos 使用	  
#endif

#if 1
#pragma import(__use_no_semihosting)             
//标准库需要的支持函数                 
struct __FILE 
{ 
	int handle; 

}; 

FILE __stdout;       
//定义_sys_exit()以避免使用半主机模式    
_sys_exit(int x) 
{ 
	x = x; 
} 
//重定义fputc函数 
int fputc(int ch, FILE *f)
{      
	while((USART1->SR&0X40)==0);//循环发送,直到发送完毕   
    USART1->DR = (u8) ch;      
	return ch;
}
#endif 

/*使用microLib的方法*/
 /* 
int fputc(int ch, FILE *f)
{
	USART_SendData(USART1, (uint8_t) ch);

	while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET) {}	
   
    return ch;
}
int GetKey (void)  { 

    while (!(USART1->SR & USART_FLAG_RXNE));

    return ((int)(USART1->DR & 0x1FF));
}
*/
 
#if EN_USART1_RX   //如果使能了接收
//串口1中断服务程序
//注意,读取USARTx->SR能避免莫名其妙的错误   	
u8 USART_RX_BUF[USART_REC_LEN];     //接收缓冲,最大USART_REC_LEN个字节.
//接收状态
//bit15,	接收完成标志
//bit14,	接收到0x0d
//bit13~0,	接收到的有效字节数目
u16 USART_RX_STA=0;       //接收状态标记	  
  
void uart_init(u32 bound){
  //GPIO端口设置
  GPIO_InitTypeDef GPIO_InitStructure;
	USART_InitTypeDef USART_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;
	 
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE);	//使能USART1,GPIOA时钟
  
	//USART1_TX   GPIOA.9
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.9
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;	//复用推挽输出
  GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化GPIOA.9
   
  //USART1_RX	  GPIOA.10初始化
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;//PA10
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空输入
  GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化GPIOA.10  

  //Usart1 NVIC 配置
  NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;//抢占优先级3
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;		//子优先级3
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;			//IRQ通道使能
	NVIC_Init(&NVIC_InitStructure);	//根据指定的参数初始化VIC寄存器
  
   //USART 初始化设置

	USART_InitStructure.USART_BaudRate = bound;//串口波特率
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长为8位数据格式
	USART_InitStructure.USART_StopBits = USART_StopBits_1;//一个停止位
	USART_InitStructure.USART_Parity = USART_Parity_No;//无奇偶校验位
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制
	USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;	//收发模式

  USART_Init(USART1, &USART_InitStructure); //初始化串口1
  USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//开启串口接受中断
  USART_Cmd(USART1, ENABLE);                    //使能串口1 

}

void USART1_IRQHandler(void)                	//串口1中断服务程序
	{
	u8 Res;
#if SYSTEM_SUPPORT_OS 		//如果SYSTEM_SUPPORT_OS为真,则需要支持OS.
	OSIntEnter();    
#endif
	if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)  //接收中断(接收到的数据必须是0x0d 0x0a结尾)
		{
		Res =USART_ReceiveData(USART1);	//读取接收到的数据
		
		if((USART_RX_STA&0x8000)==0)//接收未完成
			{
			if(USART_RX_STA&0x4000)//接收到了0x0d
				{
				if(Res!=0x0a)USART_RX_STA=0;//接收错误,重新开始
				else USART_RX_STA|=0x8000;	//接收完成了 
				}
			else //还没收到0X0D
				{	
				if(Res==0x0d)USART_RX_STA|=0x4000;
				else
					{
					USART_RX_BUF[USART_RX_STA&0X3FFF]=Res ;
					USART_RX_STA++;
					if(USART_RX_STA>(USART_REC_LEN-1))USART_RX_STA=0;//接收数据错误,重新开始接收	  
					}		 
				}
			}   		 
     } 
#if SYSTEM_SUPPORT_OS 	//如果SYSTEM_SUPPORT_OS为真,则需要支持OS.
	OSIntExit();  											 
#endif
} 
#endif	

因为只涉及距离的测量故主函数略显单薄。

main.c

#include "delay.h"
#include "sys.h"
#include "usart.h"
#include "hcsr04.h"
 
 int main(void)
 {
		 
	float length;
    
	
	 
	delay_init();	    	 //延时函数初始化	  
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //设置NVIC中断分组2:2位抢占优先级,2位响应优先级
	uart_init(115200);	 //串口初始化为115200
 	Hcsr04Init();
    
	

	
 	while(1)
	{
	
		length = Hcsr04GetLength();
		
		printf("距离为:%.3fcm  \n",length);
		
		
	}	 
 }

猜你喜欢

转载自blog.csdn.net/qqGHJ/article/details/82953252