/**
* 超聲波測距組件
* 文件名: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 <stc15f2k60s2.h>
#include <intrins.h>
#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;
}