找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 1315|回复: 0
收起左侧

智能小车超声波测距

[复制链接]
ID:189728 发表于 2017-4-15 09:47 | 显示全部楼层 |阅读模式
#include "stm32f10x_heads.h"
#include "HelloRobot.h"
#include "display.h"


void Tim2_Init(void);


void TIM2_IRQHandler(void)
{
if(GPIO_ReadInputDataBit(GPIOE,GPIO_Pin_12)==0)
GPIO_SetBits(GPIOE,GPIO_Pin_12);
else
GPIO_ResetBits(GPIOE,GPIO_Pin_12);



TIM_ClearFlag(TIM2, TIM_FLAG_Update);
}


int main(void)
{
u16 count;
float length;
BSP_Init();
Tim2_Init();//定时器初始化函数
LCM_Init();
delay_nms(5);
GPIO_ResetBits(GPIOA,GPIO_Pin_8);
Display_List_Char(1,0,"distance:"); //PA8:Trig PA0:Echo


while (1)
{
GPIO_SetBits(GPIOA,GPIO_Pin_8);
delay_nus(20);//拉高超过10us,发射超声波
GPIO_ResetBits(GPIOA,GPIO_Pin_8);

TIM2->CNT=0;//计数器清0
while(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_9)==0);//等待ECHO脚高电平

TIM_Cmd(TIM2, ENABLE);// TIM2 enable counter [允许tim2计数]


while((GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_9)==1)&&(TIM2->CNT<TIM2->ARR-10));


TIM_Cmd(TIM2, DISABLE);


count=TIM2->CNT;//ECHO脚低电平后读取计数器的值,从而算出往返时间
length=count/58.0;
Display_List_Char(1,9," ");
Display_List_Float(1,9,length);
delay_nms(200);
}
}


void Tim2_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;


TIM_DeInit(TIM2);//复位TIM2定时器
TIM_TimeBaseStructure.TIM_Period = 49999;
TIM_TimeBaseStructure.TIM_Prescaler = 71;
TIM_TimeBaseStructure.TIM_ClockDivision = 0x0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, & TIM_TimeBaseStructure);

TIM_ClearFlag(TIM2, TIM_FLAG_Update);

TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
}


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表