代碼已包括蜂鳴器 圖中并沒有顯示出蜂鳴器 需自行加入
超聲波.png (323.8 KB, 下載次數: 78)
下載附件
2020-10-5 22:58 上傳
Arduino源程序:
- #include <LiquidCrystal.h>
- const int RS=2, EN=3, DB4=4, DB5=5, DB6=6, DB7=9, beep=8;
- const int TrigPin = 13;
- const int EchoPin = 11;
- float cm;
- LiquidCrystal lcd(RS, EN, DB4, DB5, DB6, DB7);
- void setup()
- {
- lcd.begin(16,2);
- Serial.begin(9600);
- pinMode(TrigPin, OUTPUT);
- pinMode(EchoPin, INPUT);
- pinMode(13, OUTPUT);
- pinMode(beep,OUTPUT); //蜂鳴器引腳設定為輸出
- lcd.print("yan wu"); //將hello,world!顯示在LCD上
- }
- void loop()
- { digitalWrite(TrigPin, LOW); //低高低電平發一個短時間脈沖去TrigPinno
- delayMicroseconds(2);
- digitalWrite(TrigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(TrigPin, LOW);
- cm = pulseIn(EchoPin, HIGH) / 58; //將回波時間換算成cm
- cm = (int(cm * 100)) / 100; //保留兩位小數
- for(int i = 0 ; i < 100 ; i++) //循環100次
- {
- digitalWrite(beep,HIGH); //設置輸出高電平
- delayMicroseconds(220); //延時PotBuffer值 us
- digitalWrite(beep,LOW); //設置輸出低電平
- delayMicroseconds(220); //延時100us
- }
- if (cm < 10)
- {
- digitalWrite(13, HIGH);
- delay(100);
- digitalWrite(13, LOW);
- /*lcd.print(cm);
- lcd.print("cm");//串口輸出
- lcd.println();*/
- }
- else if (cm > 10 && cm < 50)
- {digitalWrite(13, HIGH);
- delay(300);
- digitalWrite(13, LOW);
- /* lcd.print(cm);
- lcd.print("cm");//串口輸出
- lcd.println();*/
- }
- else if (cm > 50)
- {digitalWrite(13, HIGH);
- delay(10);
- digitalWrite(13, LOW);
- /*lcd.print(cm);
- lcd.print("cm");//串口輸出
- lcd.println();*/
- }
- Serial.print(cm);
- Serial.print("cm");//串口輸出
- Serial.println();
- lcd.setCursor(0, 1); //將閃爍的光標設置到column 0, line 1 (注釋:從0開始數起,line 0是顯示第一行,line 1是第二行。)
- lcd.setCursor(5, 1);
- lcd.print(cm);
- lcd.setCursor(11, 1);
- lcd.print("cm");//串口輸出
- lcd.println();
- }
復制代碼
|