應(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ù)制代碼
==程序效果== 打開串口監(jiān)視器可以觀察到輸出的距離值為當(dāng)前超聲波距前方障礙物的實(shí)際距離。 |