/**
* 超声波测距组件
* 文件名:ultrasonic.h
*/
#ifndef _ULTRASONIC_H
#define _ULTRASONIC_H
#define somenop(); {
_nop_();_nop_();_nop_();_nop_();_nop_();
_nop_();_nop_();_nop_();_nop_();_nop_();
}
sbit TX = P1^0; //发射引脚
sbit RX = P1^1; //接收引脚
void tmr1_specialInit();
uint8_t ult_getDis();
#endif // _ULTRASONIC_H
/**
* 超声波测距组件
* 文件名:ultrasonic.c
*/
#include
#include
#include "stdint.h"
#include "ultrasonic.h"
/* 特殊配置定时器1,作为计时器 */
void tmr1_specialInit() { //不要开启中断,要将溢出标志位置0,不要开始运行
AUXR &= 0xBF;
TMOD &= 0x0F;
TMOD |= 0x10;
TL1 = 0; //!!!
TH1 = 0; //!!!
TF1 = 0; //!!!
}
//TX引脚发送40KHz方波信号驱动超声波发送探头
static void ult_sendWave() {
uint8_t cnt = 8; //发送8个脉冲
EA = 0; //!!!
do {
TX = 1;
somenop(); //保持TX一段时间
TX = 0;
somenop(); //保持TX一段时间
} while (--cnt);
EA = 1; //!!!
}
uint8_t ult_getDis() {
uint16_t count; //定时器1的计数值,即为时间间隔
uint8_t distance; //单位为cm,实测最大测量距离约为90cm
RX = 1; //!!
ult_sendWave(); //发送方波信号
TR1 = 1; //启动计时
while ((RX == 1) && (TF1 == 0)); //等待收到脉冲
TR1 = 0; //关闭计时
if (TF1 == 1) { //如果定时器发生溢出,则超过量程
TF1 = 0;
distance = 0xFF; //无返回,距离为无穷远
} else {
count = TH1;
count <<= 8;
count |= TL1;
distance = (uint8_t)((uint32_t)count * 17 / 1000); //计算距离(cm)
}
TH1 = 0; //重新复位定时器,为下次测量做好准备
TL1 = 0;
return distance;
}
『本文转载自网络,版权归原作者所有,如有侵权请联系删除』