``````// --------------------------------------------------------------------------------
/*

16 顯示超聲波感應器取得的距離

[學習重點]

1. 認識超聲波感應器

https://create.arduino.cc/projecthub/abdularbi17/ultrasonic-sensor-hc-sr04-with-arduino-tutorial-327ff6

[挑戰]

- 研究如何干擾超聲波感應器
例如利用某些材料去吸收感應器發出的超聲波之類

Created by Jason on 16 Aug 2022.

*/
// --------------------------------------------------------------------------------

// LCD
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

// HC-SR04
#define echoPin 2 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 3 //attach pin D3 Arduino to pin Trig of HC-SR04
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

void setup() {
// LCD
lcd.init();
lcd.backlight();

// HC-SR04
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
}

void loop() {
// HC-SR04
digitalWrite(trigPin, LOW); // Clears the trigPin condition
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
distance = duration * 0.034 / 2; // Calculating the distance - Speed of sound wave divided by 2 (go and back)

// 顯示文字訊息到 LCD
lcd.setCursor(5,1); // 設定遊標位置 (左邊數第幾個字, 行數)
lcd.print("Distance:"); // 在遊標位置顯示文字
lcd.setCursor(5,2);
lcd.print(distance);
lcd.print(" cm   ");

delay(100);
}``````