かんたくんのやつです。
Fork of HCSR04 by
Revision 8:0fda00df4357, committed 2018-09-22
- Comitter:
- tektomo
- Date:
- Sat Sep 22 11:00:29 2018 +0000
- Parent:
- 7:71da0dbf4400
- Commit message:
- ????????
Changed in this revision
hcsr04.cpp | Show annotated file Show diff for this revision Revisions of this file |
hcsr04.h | Show annotated file Show diff for this revision Revisions of this file |
--- a/hcsr04.cpp Sat Mar 30 18:55:03 2013 +0000 +++ b/hcsr04.cpp Sat Sep 22 11:00:29 2018 +0000 @@ -18,12 +18,17 @@ */ + + #include "hcsr04.h" + + HCSR04::HCSR04(PinName TrigPin,PinName EchoPin): trigger(TrigPin), echo(EchoPin) { + setTemp(15); pulsetime.stop(); pulsetime.reset(); echo.rise(this,&HCSR04::isr_rise); @@ -31,29 +36,48 @@ trigger=0; } + HCSR04::~HCSR04() { } + +void HCSR04::start(void) +{ + pulsetime_us = pulsetime.read_us(); + if(pulsetime_us > maxTime){ + pulsetime.stop(); + pulsetime.reset(); + trigger=1; + trigger=0; + } + trigger=1; + wait_us(10); + trigger=0; +} + + void HCSR04::isr_rise(void) { pulsetime.start(); } -void HCSR04::start(void) -{ - trigger=1; - wait_us(10); - trigger=0; -} + void HCSR04::isr_fall(void) { pulsetime.stop(); - pulsedur = pulsetime.read_us(); - distance= (pulsedur*343)/20000; + pulsetime_us = pulsetime.read_us(); + if(pulsetime_us > maxTime){ + trigger=1; + trigger=0; + distance = 0; + }else{ + distance = pulsetime_us*sonic/20000; + } pulsetime.reset(); } + void HCSR04::rise (void (*fptr)(void)) { echo.rise(fptr); @@ -63,36 +87,15 @@ echo.fall(fptr); } + unsigned int HCSR04::get_dist_cm() { return distance; } -unsigned int HCSR04::get_pulse_us() -{ - return pulsedur; -} - -/******************************************************* - Here is a sample code usage -********************************************************* -#include "hcsr04.h" -HCSR04 usensor(p25,p6); -int main() -{ - unsigned char count=0; - while(1) { - usensor.start(); - wait_ms(500); - dist=usensor.get_dist_cm(); - lcd.cls(); - lcd.locate(0,0); - lcd.printf("cm:%ld",dist ); - - count++; - lcd.locate(0,1); - lcd.printf("Distance =%d",count); - - } -*/ \ No newline at end of file +void HCSR04::setTemp(int temp){ + temperature = temp; + sonic = 331.5+0.61*temperature; + maxTime = 10*1000000/sonic; +} \ No newline at end of file
--- a/hcsr04.h Sat Mar 30 18:55:03 2013 +0000 +++ b/hcsr04.h Sat Sep 22 11:00:29 2018 +0000 @@ -53,16 +53,19 @@ void isr_fall(void); void fall (void (*fptr)(void)); void rise (void (*fptr)(void)); - - + + void setTemp(int temp); private: Timer pulsetime; + float pulsetime_us; + unsigned int distance; + int temperature; + double maxTime; + double sonic; DigitalOut trigger; InterruptIn echo; - unsigned int pulsedur; - unsigned int distance; }; #endif \ No newline at end of file