写一个超声波传感器块里面包含有Init 和打开和关闭超声波模块以下是程序
#include "stm32f10x.h"
#include "SR_04.h"
extern uint32_t mun = 0;
void GPIO_init()//初始化
{
GPIO_InitTypeDef GPIO_Tirg;
GPIO_InitTypeDef GPIO_Echo;
TIM_TimeBaseInitTypeDef TIM_GPIO;
NVIC_InitTypeDef NVIC_GPIO;
RCC_APB2PeriphResetCmd(RCC_APB2Periph_AFIO,ENABLE);
RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOA,ENABLE);
RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM2,ENABLE);
GPIO_Tirg.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Tirg.GPIO_Pin = GPIO_Pin_9;
GPIO_Tirg.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Echo.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Echo.GPIO_Pin = GPIO_Pin_10;
GPIO_Echo.GPIO_Speed = GPIO_Speed_50MHz;
TIM_GPIO.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_GPIO.TIM_CounterMode = TIM_CounterMode_Up;
TIM_GPIO.TIM_Period = 100-1;
TIM_GPIO.TIM_Prescaler = 72-1;
NVIC_GPIO.NVIC_IRQChannel = TIM2_IRQn;
NVIC_GPIO.NVIC_IRQChannelCmd = ENABLE;
NVIC_GPIO.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_GPIO.NVIC_IRQChannelSubPriority = 1;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_Init(&NVIC_GPIO);
GPIO_Init(GPIOA,&GPIO_Tirg);
GPIO_Init(GPIOA,&GPIO_Echo);
TIM_TimeBaseInit(TIM2,&TIM_GPIO);
TIM_Cmd(TIM2,DISABLE);
TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
}
void Open_TIM()//打开定时器
{
TIM_SetCounter(TIM2,0);
mun++;
TIM_Cmd(TIM2,ENABLE);
}
void Close_TIM()//关闭定时器
{
TIM_Cmd(TIM2,DISABLE);
}
int Get_time()//获取定时器数值
{
uint32_t t = 0;
t = mun*1000;
t = TIM_GetCounter(TIM2);
TIM2->CNT = 0;
return t;
}
float Get_long()//计算长度
{
int i = 0;
uint32_t t = 0;
float leng = 0.0;
float sum = 0.0;
float V_leng = 0.0
Open_TIM();
while(i != 5)
{
Tirg_SR(1);
us_delay(20);
Tirg_SR(0);
while(Echo_SR == 0)
{
Open_TIM();
i++;
}
while(Echo_SR == 1)
{
Close_TIM();
t = Get_time();
leng = (float)t/58.0;
sum = sum+leng;
}
}
V_leng = sum/5.0;
return V_leng;
}
这个是.c的文件下面是.h的定义
#include "stm32f10x.h"
void GPIO_init();
void Open_TIM();
void Close_TIM();
int Get_time();
float Get_long();
#define Echo_SR GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_9)
#define Tirg_SR(a) if(a==1)\
GPIO_SetBits(GPIOA,GPIO_Pin_10);\
else\
GPIO_ResetBits(GPIOA,GPIO_Pin_10)