Arduino uno使用HC-SR04超声波测距在LCD上显示

接线图如图所示:

Arduino uno使用HC-SR04超声波测距在LCD上显示_第1张图片

代码如下:


#include 
const int RS=2, EN=3, DB4=4, DB5=5, DB6=6, DB7=9, Trig=7, Echo=8;
float Dist;
LiquidCrystal lcd(RS, EN, DB4, DB5, DB6, DB7);

void setup(){
    lcd.begin(16,2);
    pinMode(Trig, OUTPUT);
    pinMode(Echo, INPUT);
}

void loop(){
    long Time=0;
    while(1){
        digitalWrite(Trig, HIGH);
        delayMicroseconds(10);
        digitalWrite(Trig, LOW);
        Time = pulseIn(Echo, HIGH);
        Dist = Time/58.00;
        if(Dist < 300){
            lcd.setCursor(1, 0);
            lcd.print("Dist");
            lcd.print(Dist);
            lcd.print(" cm ");
            }
        Dist = 0;
        Time = 0;
        delay(500);
    }
}

实物效果如下图所示:

Arduino uno使用HC-SR04超声波测距在LCD上显示_第2张图片

你可能感兴趣的:(Ardunio)