INCTRC Information Sharing Test
/
UltraSonic
大昔の超音波センサプログラム
main.cpp
- Committer:
- yuron
- Date:
- 2018-07-14
- Revision:
- 0:f43a798a392d
File content as of revision 0:f43a798a392d:
/* ちょうおんぱせんさHC-SR04をしよう LCDにきょりをひょうじ 30cmいかのきょりならばLEDがひかる */ #include "mbed.h" #include "TextLCD.h" TextLCD lcd(D12, D11, D10, D9, D8, D7, TextLCD::LCD20x2); // rs, e, d4-d7 DigitalOut trigger(D15); DigitalOut myled(LED1); DigitalIn echo(D14); int distance = 0; int correction = 0; Timer sonar; int main() { sonar.reset(); while(1) { // trigger sonar to send a ping trigger = 1; sonar.reset(); wait_us(10.0); trigger = 0; //wait for echo high while (echo==0) {}; //echo high, so start timer sonar.start(); //wait for echo low while (echo==1) {}; //stop timer and read value sonar.stop(); //subtract software overhead timer delay and scale to cm distance = (sonar.read_us()-correction)/58.0; if(distance <= 30){ myled = 1; } else { myled = 0; } lcd.printf("%d cm \n\r",distance); //wait so that any echo(s) return before sending another ping wait(0.2); } }