---
# System prepended metadata

title: HC-SR04 + LCD1602 + KY-016 + KY-17

---

# HC-SR04 + LCD1602 + KY-016 + KY-17
## 程式碼：

``` c =
#include<LCD_I2C.h>

LCD_I2C lcd(0x27, 16, 2); //(顯示器行號/單行字數/行數)
int trigPin = 11; //Trig Pin 傳送超聲波
int echoPin = 12; //Echo Pin 接收超聲波
int buttonpin = 3 ;
int val ;
int redpin = 10 ;
int greenpin = 9 ;
int bluepin = 8 ;
int val2 ;
float duration, cm, inches;

void setup(){

  pinMode(redpin,OUTPUT);
  pinMode(bluepin,OUTPUT);
  pinMode(greenpin,OUTPUT);
  Serial.begin (9600);      // 通訊頻率設定
  pinMode(trigPin, OUTPUT); // 定義輸入及輸出
  pinMode(echoPin, INPUT);

  pinMode(buttonpin , INPUT);
  
  lcd.begin();
  for(int i = 0; i < 3; i++) {
    lcd.backlight(); // 開啟背光
    delay(250);
    lcd.noBacklight(); // 關閉背光
    delay(250);
  }
  lcd.backlight();
  lcd.setCursor(0, 0); // 設定游標位置在第一行行首
  delay(1000);

}
void loop(){
  
  val = digitalRead (buttonpin);
  if (val == HIGH )
  {
    digitalWrite(trigPin, LOW);
    delayMicroseconds(5);
    digitalWrite(trigPin, HIGH); // 給 Trig 高電位,持續 10 微秒
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    pinMode(echoPin, INPUT); // 讀取 echo 的電位
    duration = pulseIn(echoPin, HIGH); // 收到高電位時的時間
    cm = (duration/2) / 29.1; // 將時間換算成距離 cm 或 inch
    inches = (duration/2) / 74;

    delay(200);
    
    if (duration) {
      delay(100); // 等待一小段時間，確認資料都接收下來了
      lcd.clear(); // 清除舊訊息
      lcd.setCursor(0, 0); // 設定游標位置在第一行行首
      lcd.print(inches);
      lcd.setCursor(14, 0);
      lcd.print("in");
      lcd.setCursor(0, 1); // 設定游標位置在第二行行首
      lcd.print(cm);
      lcd.setCursor(14, 1);
      lcd.print("cm");
      
      for(val2 = 150 ; val2 < 200 ; val2 ++  ) {
      
        analogWrite(11 , val2 );
        analogWrite(10 , 255 - val2 );
        analogWrite(9 , 128 - val2 );
        Serial.println(val2 , DEC);
        delay(5);
          
      }
      for(val2 = 200 ; val2 > 150 ; val2 --  ) {
          
        analogWrite(11 , val2 );
        analogWrite(10 , 255 - val2 );
        analogWrite(9 , 128 - val2 );
        Serial.println(val2 , DEC);
        delay(5);
          
      }
      delay(500);
    
    }
    
  }
  else {
    lcd.clear(); // 清除舊訊息
    lcd.setCursor(0, 0); // 設定游標位置在第一行行首
    lcd.print("Button is LOW");
   
    
    
     for(val2 = 60 ; val2 > 50 ; val2 -- ) {
      analogWrite(11 , val2 );
      analogWrite(10 , 255 - val2 );
      analogWrite(9 , 128 - val2 );
      Serial.println(val2 , DEC);
      delay(5);
    }
    for(val2 = 50 ; val2 < 60 ; val2 ++ ) {
      analogWrite(11 , val2 );
      analogWrite(10 , 255 - val2 );
      analogWrite(9 , 128 - val2 );
      Serial.println(val2 , DEC);
      delay(5);
    }
      
    delay(500) ; 
  }
  
  
}