US-020超声波模块驱动(STM32)

一、前期准备
单片机:STM32F103C8T6
开发环境:MDK5.14
库函数:标准库V3.5
US-020模块:淘宝有售
US-020超声波模块驱动(STM32)_第1张图片

二、实验效果
在这里插入图片描述
US-020超声波模块驱动(STM32)_第2张图片

三、驱动原理
触发信号Tirig维持10Us以上的高电平即可等待Echo的返回,这里是用EXTI检测俩个跳变信号,去打开和关闭定时器,最后一次测量计算结果后清除定时器计时,并等待下一个循环开始。需要完整工程或者有问题的请加QQ:1002521871,验证:呵呵。

四、驱动代码
US-020.h

#ifndef __US_020_H__
#define	__US_020_H__
#include "stm32f10x.h"
#include "gpio.h"
#include "delay.h"

#define			Trig			PAout(0)
#define			Trig_Pin		GPIO_Pin_0
#define			Trig_Port		GPIOA
#define			Trig_CLKLine	RCC_APB2Periph_GPIOA
#define			Echo			PAin(1)
#define			Echo_Pin		GPIO_Pin_1
#define			Echo_Port		GPIOA
#define			Echo_CLKLine	RCC_APB2Periph_GPIOA

extern uint32_t US_Count;
extern void US_020Configuration(void);
extern void US_SendStartSignal(void);
extern float US_DataConversion(uint32_t *count);
#endif

US-020.c

#include "US-020.h"

uint32_t US_Count = 0;
void US_020Configuration(void)
{
	GPIO_InitTypeDef    GPIO;
    NVIC_InitTypeDef 	MyNVIC;	
	EXTI_InitTypeDef	MyEXTI;
    //Enable APB2 Bus
    RCC_APB2PeriphClockCmd(Trig_CLKLine | Echo_CLKLine, ENABLE);
    
    //Register IO 
    GPIO.GPIO_Pin   = Trig_Pin;
    GPIO.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO.GPIO_Mode  = GPIO_Mode_Out_PP;
    GPIO_Init(Trig_Port, &GPIO);
	
	Trig = 0;
	//Register IO 
    GPIO.GPIO_Pin   = Echo_Pin;
    GPIO.GPIO_Mode  = GPIO_Mode_IN_FLOATING;
    GPIO_Init(Echo_Port, &GPIO);
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);				//设置中断优先级组为1,优先组(可设0~4位)
	
	MyNVIC.NVIC_IRQChannel = EXTI1_IRQn;				//设置中断向量号
	MyNVIC.NVIC_IRQChannelPreemptionPriority = 0;	//设置抢先优先级
	MyNVIC.NVIC_IRQChannelSubPriority = 1;			//设置响应优先级
	MyNVIC.NVIC_IRQChannelCmd = ENABLE;				//使能NVIC
	NVIC_Init(&MyNVIC);
	
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource1);
	MyEXTI.EXTI_Line	= EXTI_Line1;
	MyEXTI.EXTI_Trigger = EXTI_Trigger_Rising_Falling;
	MyEXTI.EXTI_Mode	= EXTI_Mode_Interrupt;
	MyEXTI.EXTI_LineCmd	= ENABLE;
	EXTI_Init(&MyEXTI);
}

void US_SendStartSignal(void)
{
	Trig = 1;
	DelayUs(20);
	Trig = 0;
}
	
float US_DataConversion(uint32_t *count)
{
	float result = 0;
	result = (float)((float)(*count * 340) / 2000.0);
	*count = 0;
	return result;
}

void EXTI1_IRQHandler(void)
{
	if (EXTI_GetITStatus(EXTI_Line1) != RESET) 
	{ 
		EXTI_ClearITPendingBit(EXTI_Line1);
		if (Echo == 1)
		{
			TIM_Cmd(TIM3, ENABLE);  
			LED = 0;
		}
		
		if (Echo == 0)
		{
			TIM_Cmd(TIM3, DISABLE);  
			LED = 1;
		}
	}
}

由于作者能力有限,有不妥之处欢迎指正,邮箱[email protected]

你可能感兴趣的:(嵌入式常用模块驱动)