割り込みを利用して超音波測距センサーをバックグラウンドで計測し続けられます。
Dependents: escapeFromYou Sample_LinetraceWithSonicDist
Diff: SonicDist.cpp
- Revision:
- 3:b22567a5f7d6
- Child:
- 4:84f4fa630726
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/SonicDist.cpp Sat Jul 09 15:10:17 2016 +0000 @@ -0,0 +1,74 @@ +#include "mbed.h" +#include "SonicDist.h" +SonicDist::SonicDist(PinName Trig, PinName Echo){ + trig=new DigitalOut(Trig); + echopin=Echo; + // echo=new InterruptIn(Echo); + soundspeed=340; + startflag=false; + trig->write(1); + setmeasure=true; +} +void SonicDist::init(void){ + DigitalIn Ec(echopin); + echotime.stop(); + echotime.reset(); + trig->write(1); + wait(0.000010); + trig->write(0); + wait(0.000014); + trig->write(1); + while(Ec==0); + SonicDist::StartMeasure(); + while(Ec==1||(double)echotime.read()<0.007); + SonicDist::endMeasure(); + // Ec.dispose(); + echo=new InterruptIn(echopin); + echo->rise( this, &SonicDist::StartMeasure ); + echo->fall( this, &SonicDist::endMeasure ); + SonicDist::setTrig(); +} +void SonicDist::StartMeasure(void){ + echotime.reset(); + echotime.start(); + startflag=true; +} +void SonicDist::endMeasure(void){ + SonicDist::CalcDist(); + systime.detach(); + SonicDist::setTrig(); +} +void SonicDist::CalcDist(void){ + if(startflag){ + echotime.stop(); + dist=echotime.read()*soundspeed*1000/2;//mmで出力 + startflag=false; + } +} +void SonicDist::setTrig(void){ + trig->write(0); + systime.attach(this,&SonicDist::releaseTrig, 0.000014); +} +void SonicDist::releaseTrig(void){ + trig->write(1); + systime.attach(this,&SonicDist::timeout, 0.007); +} +void SonicDist::timeout(void){ + SonicDist::CalcDist(); + SonicDist::setTrig(); + if(startflag){printf("a");} +} +double SonicDist::getDist(void){ + if(setmeasure){ + SonicDist::init(); + setmeasure=false; + } + return (double)dist/10; +} +double SonicDist::getDist_mm(void){ + if(setmeasure){ + SonicDist::init(); + setmeasure=false; + } + return dist; +}