x @sasakisanさんの記事を非営利、研究目的で参考にして移植しました。
目的
HC_SR04からのPWMの受信
Keil Studio用に焼き直し
//Keil Studio ( mbed2 )
//serial_HC_SR04_812_1
#include "mbed.h"
Serial pc(USBTX, USBRX); // tx, rx
#define HIGH 1
DigitalOut TRIG(P0_17); //green D8
DigitalIn ECHO(P0_7); //red D7
//タイマーの設定
Timer t;
//PA_5のオン時間をusで測る 今のところ引数は、無効
int pulseIn(int pin1,int pu1,int timeout1)
{
t.reset();//タイマーの開始
//タイムアウトの設定
//timeout1 = 32000000;
timeout1 = 100000; //28ms
//timeout1 = 1000; //degbu
//while(PA_5 == 0) {} //オフの間は、無限ループ
loop_s1:
timeout1--;
// 5432109876543210
if ( (~(LPC_GPIO_PORT->PIN0)) & 0b0000000010000000 ) {
if ( timeout1 ) {
goto loop_s1;
}
}
int sd = t.read_us();//測定開始
//タイムアウトの設定
//timeout1 = 32000000;
timeout1 = 100000; //28ms
//timeout1 = 1000; //degbu
//while(PA_5 != 0) {} //オンの間は、無限ループ
loop_in1:
timeout1--;
// 5432109876543210
if ( (LPC_GPIO_PORT->PIN0) & 0b0000000010000000 ) {
if( timeout1 ) {
goto loop_in1;
}
}
return(t.read_us()-sd);//測定終了
}//pulseIn
//メインルーチン
int main() {
unsigned long times; //測定時間
int distance; //長さ 単位は、mm
//タイマーの開始
t.start();
// GPIOの初期化
TRIG = 0;
//無限ループ
while (1) {
// 超音波を発生させる
TRIG = 1;
wait_us(10);
TRIG = 0;
// 超音波を受け取る
times = pulseIn( 5, HIGH,2000000);
// times = (unsigned long)7700/2; //debug
// times = 1177; // debug 1ms 20.0cm
// times = 942;//debug 1ms 16.0cm
//時間を距離に変換する 音は、1秒間に約340メートル進む
//速さx時間は距離
//まず往復なので1/2にする
// times/2
// 340 x (times / 1000) 単位が秒なのでそろえてあげる
// distance = (int)(times * 0.017);
distance = (int)((times * ((unsigned long)(17))) / 100);
//距離の表示
pc.printf("%d\n\r", distance);
wait_us(500 * 1000); // 0.5秒待つ
} // while
} // main