[mw_shl_code=c,true]
[/mw_shl_code]
[mw_shl_code=c,true]我换了一种方式实验 :按一下按键(3个按键随便一个)就进行一次测距 向串口打印SysTick计数值[/mw_shl_code]
[mw_shl_code=c,true]以下是代码:[/mw_shl_code]
[mw_shl_code=c,true]
[/mw_shl_code]
[mw_shl_code=c,true]#include "led.h"
#include "delay.h"
#include "sys.h"
#include "key.h"
#include "usart.h"
//ALIENTEK Mini STM32开发板范例代码2
//按键输入实验
//技术支持:www.openedv.com
//广州市星翼电子科技有限公司
int main(void)
{
u8 t=0;
u32 timeVal;
GPIO_InitTypeDef GPIO_InitStructure;
uart_init(9600);
delay_init();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; //PB5
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; //设置为下拉输入 echo
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; //PB6
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //设置为推挽输出 Trig
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_ResetBits(GPIOB,GPIO_Pin_6);//初始设置为低电平
KEY_Init(); //初始化与按键连接的硬件接口
while(1)
{
t=KEY_Scan(0); //得到键值
if(t==KEY0_PRES||t==KEY1_PRES||t==WKUP_PRES)//如果三个按键有一个按下了 就进行一次测距
{
printf("one try\n");
delay_ms(1000);
SysTick->LOAD=20000000;
SysTick->VAL=0x00; //对sysTick进行初始设置 为一会定时做铺垫
//计算了一下 在72MHz的8分频下 最大测距4m 对应Systick计数减掉21600 所以这里的初值够用
GPIO_SetBits(GPIOB,GPIO_Pin_6);
delay_us(15);
GPIO_ResetBits(GPIOB,GPIO_Pin_6);//发送了一个长达15us的脉冲
while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_5)!=1)//等待echo发回一个高电平脉冲
printf("=0\n");
SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk ; //开启定时器
printf("sended one wave\n");
while(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_5)!=0)//等待echo的高电平脉冲结束
printf("=1\n");
timeVal=SysTick->VAL;//记录了echo脉冲结束时SysTick的计数值
SysTick->CTRL&=~SysTick_CTRL_ENABLE_Msk; //
SysTick->VAL =0X00; //关闭计数器
printf("%ds",timeVal);//向串口打印测距对应的计数值
printf("\n");
printf("one try completed\n");
}
}
}
[/mw_shl_code]
但结果还是有问题
测的稍微远一点不论多远结果都差不多
太近就一直检测不到echo的脉冲
这是模块的时序图
:
|