stm32之14.超声波测距代码


源码

void sr04_init(void)

{

GPIO_InitTypeDef GPIO_InitStructure;

//打开端口B的硬件时钟,就是供电

RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC,ENABLE);

//打开端口E的硬件时钟,就是供电

RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE,ENABLE);

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; //6号引脚

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; //输入模式

GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;//推挽输出

GPIO_InitStructure.GPIO_Speed = GPIO_High_Speed;//高速,速度越高,响应越快,但是功耗会更高

GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;//不使能上下拉电阻(因为外部已经有上拉电阻)

GPIO_Init(GPIOE,&GPIO_InitStructure);

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7; //6号引脚

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; //输出模式

GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;//推挽输出

GPIO_InitStructure.GPIO_Speed = GPIO_High_Speed;//高速,速度越高,响应越快,但是功耗会更高

GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;//不使能上下拉电阻(因为外部已经有上拉电阻)

GPIO_Init(GPIOC,&GPIO_InitStructure);

//只要有输出模式,肯定会有初始化电平的状态,看连接设备说明书

PCout(7)=0;

}

int32_t sr04_get_distance(void)

{

uint32_t t=0;

PCout(7)=1;

delay_us(10);

PCout(7)=0;

//等待回响信号,若等待成功,PE6引脚为高电平,则跳出该循环

while(PEin(6)==0);

//测量高电平的持续时间

while(PEin(6))

{

t++;

delay_us(9); //有多少个9us ,就是有多少个3mm

}

//因为超声波的传输时间是发射时间+返回时间,所以需要除以/2

t=t/2;

return 3*t;

}

int main(void)

{

uint32_t distance;

NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);

//抢占优先级0~3,支持4级!

//响应优先级0~3,支持4级!

key_init();

Led_init();

//初始化串口1波特率位115200bps,若发送/接收数据有乱码,请检查PLL

usart1_init(115200);

sr04_init();

while(1)

{

distance = sr04_get_distance();

if(distance >=20 && distance<=4000)

{

printf("distance = %d mm\r\n",distance);

}

//官方要求,时间间隔60ms以上,防止发射信号对反射信号的干扰

delay_ms(1000);

}

}

相关推荐
promising-w8 小时前
【运算放大器专题】基础篇
嵌入式硬件·学习
leo03088 小时前
图像硬解码和软解码
单片机·嵌入式硬件
Wythzhfrey9 小时前
单片机总复习
单片机·嵌入式硬件
源远流长jerry9 小时前
STM32F103ZET6按键中断控制灯
stm32·单片机·嵌入式硬件
搬砖的小码农_Sky10 小时前
单片机STM32F103:DMA的原理以及应用
stm32·单片机
不想学习\??!11 小时前
STM32-待机唤醒实验
stm32·单片机·嵌入式硬件
不想学习\??!12 小时前
STM32-中断
单片机·嵌入式硬件
aerror12 小时前
xbox one controller DSLogic 逻辑分析仪截包
stm32·嵌入式硬件·xbox
TianYaKe-天涯客12 小时前
嵌入式调试LOG日志输出(以STM32为例)
stm32·单片机·嵌入式硬件
芯岭技术12 小时前
MS32C001-C单片机,32位ARM M0+内核,宽电压、低功耗、小封装。
c语言·arm开发·单片机