標(biāo)題: Arduino超聲波模塊測(cè)試源程序 能測(cè)出實(shí)時(shí)距離 [打印本頁(yè)]
作者: Edmundshi 時(shí)間: 2018-4-11 15:46
標(biāo)題: Arduino超聲波模塊測(cè)試源程序 能測(cè)出實(shí)時(shí)距離
應(yīng)用示例
電路連接
超聲波模塊 | Arduino UNO |
VCC | +5V |
Trig | A2 |
Echo | A3 |
GND | GND |
示例代碼
- //HC_SR04 Test
-
- const int TrigPin = A2;
- const int EchoPin = A3;
- float cm;
-
- void setup()
- {
- Serial.begin(9600);
- pinMode(TrigPin, OUTPUT);
- pinMode(EchoPin, INPUT);
- }
- void loop()
- {
- digitalWrite(TrigPin, LOW);
- delayMicroseconds(2);
- digitalWrite(TrigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(TrigPin, LOW);
-
- cm = pulseIn(EchoPin, HIGH) / 58.0; //echo time conversion into a distance
- cm = (int(cm * 100.0)) / 100.0; //keep two decimal places
- Serial.print(cm);
- Serial.print("cm");
- Serial.println();
- delay(1000);
- }
復(fù)制代碼
程序運(yùn)行結(jié)果:超聲波對(duì)著墻,測(cè)出實(shí)時(shí)距離,結(jié)果如圖:
注意:TRIP引腳是內(nèi)部上拉10K的電阻,用單片機(jī)的IO口拉低TRIP引腳,然后給一個(gè)10us以上的脈沖信號(hào)。
===接線方法===
*uno-SR04
*2-TRIG
*3-ECHO
*5V- VCC
*GND- GND
- const int TrigPin = 2;
- const int EchoPin = 3;
- float distance;
- void setup()
- {
- Serial.begin(9600);
- pinMode(TrigPin, OUTPUT);
- pinMode(EchoPin, INPUT);
- Serial.println("Ultrasonic sensor:");
- }
- void loop()
- {
- //發(fā)一個(gè)10μs的高脈沖去觸發(fā)TrigPin
- digitalWrite(TrigPin, LOW);
- delayMicroseconds(2);
- digitalWrite(TrigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(TrigPin, LOW);
- distance = pulseIn(EchoPin, HIGH) / 58.0; //算成厘米
- Serial.print(distance);
- Serial.print("cm");
- Serial.println();
- delay(1000);
- }
復(fù)制代碼
==程序效果==
打開(kāi)串口監(jiān)視器可以觀察到輸出的距離值為當(dāng)前超聲波距前方障礙物的實(shí)際距離。
-
-
Arduino測(cè)試程序.zip
2018-4-11 15:45 上傳
點(diǎn)擊文件名下載附件
下載積分: 黑幣 -5
161.67 KB, 下載次數(shù): 12, 下載積分: 黑幣 -5
作者: rsurb0371 時(shí)間: 2021-1-11 13:30
超聲波測(cè)距 居然能精確到小數(shù)點(diǎn) 后兩位?
作者: zhangleixbyl 時(shí)間: 2021-1-16 07:20
比51單片機(jī)簡(jiǎn)單多了
| 歡迎光臨 (http://m.raoushi.com/bbs/) |
Powered by Discuz! X3.1 |