|
實(shí)現(xiàn)的就是用超聲波模塊測(cè)距,然后用1602顯示距離,實(shí)現(xiàn)了一個(gè)電子尺的功能代碼
#include <LiquidCrystal.h>
const int TrigPin=2;
const int EchoPin=3;
float distance;
LiquidCrystal lcd(12,11,7,6,5,4);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(TrigPin,OUTPUT);
pinMode(EchoPin,INPUT);
Serial.println("超聲波傳感器");
lcd.begin(16,2);
lcd.print("Ultrasonic");
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(TrigPin,LOW); //置低
delayMicroseconds(2);
digitalWrite(TrigPin,HIGH); //觸發(fā)脈沖
delayMicroseconds(10);
digitalWrite(TrigPin,LOW);
distance=pulseIn(EchoPin,HIGH)/58.00; //距離計(jì)算公式 時(shí)間*速度
//串口
/* Serial.print(distance);
Serial.print("cm");
Serial.println();
*/
lcd.setCursor(0,1); //LCD顯示,距離從第二行開(kāi)始
lcd.print(distance);
lcd.print("cm");
delay(1000); //刷新時(shí)間
}
|
|