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);

}

}

相关推荐
scilwb9 小时前
RoboCon考核题——scilwb
单片机
点灯小铭10 小时前
基于STM32单片机智能RFID刷卡汽车位锁桩设计
stm32·单片机·汽车·毕业设计·课程设计
bai54593611 小时前
STM32 软件I2C读写MPU6050
stm32·单片机·嵌入式硬件
逼子格13 小时前
AT89C52单片机介绍
单片机·嵌入式硬件·51单片机·硬件工程师·硬件工程师真题·at89c52·器件手册
生涯にわたる学び15 小时前
ARM 实操 流水灯 按键控制 day53
arm开发·嵌入式硬件
whaosoft-14315 小时前
w嵌入式分享合集68
嵌入式硬件
竹照煜_ysn18 小时前
STM32——软硬件I2C
stm32·嵌入式硬件·mongodb
Ronin-Lotus19 小时前
嵌入式硬件篇---电感串并联
嵌入式硬件
Wallace Zhang19 小时前
STM32 - Embedded IDE - GCC - 显著减少固件的体积
stm32·单片机·嵌入式硬件
fengfuyao9851 天前
STM32如何定位HardFault错误,一种实用方法
stm32·单片机·嵌入式硬件