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

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);
}
uno:A5.2
uno:A4.2
uno:AREF
uno:GND.1
uno:13
uno:12
uno:11
uno:10
uno:9
uno:8
uno:7
uno:6
uno:5
uno:4
uno:3
uno:2
uno:1
uno:0
uno:IOREF
uno:RESET
uno:3.3V
uno:5V
uno:GND.2
uno:GND.3
uno:VIN
uno:A0
uno:A1
uno:A2
uno:A3
uno:A4
uno:A5
lcd:GND
lcd:VCC
lcd:SDA
lcd:SCL
ultrasonic1:VCC
ultrasonic1:TRIG
ultrasonic1:ECHO
ultrasonic1:GND