#include <LiquidCrystal_I2C.h>
#include <MsTimer2.h>
 
// HC-SR04 
#define triggerPin 8
#define echoPin 9
// I2C CLCD address 
#define lcdAddress 0x27
#define lcdColumns 16
#define lcdRows 2
 
LiquidCrystal_I2C lcd(lcdAddress, lcdColumns, lcdRows);
 
// mm, inch 
double distanceMm;
double distanceInch;
 
// CLCD 
String mm;
String inch;
 
// 
int flag = 0; 
 
void setup() {
    pinMode(triggerPin, OUTPUT); 
    pinMode(echoPin, INPUT); 
 
    MsTimer2::stop();
    MsTimer2::set(200, myTimer);
    MsTimer2::start();
 
    lcd.init();
    lcd.backlight();
    lcd.clear();
}
 
void loop() {
    
    
    if(flag == 1)
    {
        flag = 0;
        // HC-SR04 거리 측정
        getDistance();
        // 측정한 거리 CLCD 출력
        printDistanceLCD();
    }   
}
 
void myTimer()
{
    flag = 1;
}
 
void getDistance(){
again:
    // goto 
    static int count;
    // Tigger High 
    digitalWrite(triggerPin, LOW);
    delayMicroseconds(2);
    digitalWrite(triggerPin, HIGH);
    delayMicroseconds(10); 
    digitalWrite(triggerPin, LOW); 
    
    //echoPin High
    double Duration = 0;
    Duration = pulseIn(echoPin, HIGH); 
    
    distanceMm = Duration / 5.8;
    distanceInch = Duration / 148;
    
    
    if ((distanceMm > 4000) && (count < 10)){
        count++;
        goto again;
    }
    // 
    else if(count >= 10){
        distanceMm = 9999;
        distanceInch = 9999;
    }
    count = 0;
}
 
void printDistanceLCD(){
    // LCD Clear()
    // LCD Clear()
    int mmBlank;
    int inchBlank;
 
    // CLCD 에 출력할 데이터를 문자열로 변경
    mm = "mm   : " + String(distanceMm);
    inch = "inch : " + String(distanceInch);
    
    // 문자열의 공백 저장
    mmBlank = lcdColumns - mm.length();
    inchBlank = lcdColumns - inch.length();
 
    //CLCD 첫번째 줄
    lcd.setCursor(0,0);
    lcd.print(mm);
    for(int i = 0 ; i < mmBlank ; i++){
        lcd.print(" ");
    }
    //CLCD 2번째 줄
    lcd.setCursor(0,1);
    lcd.print(inch); 
    for(int i = 0 ; i < inchBlank ; i++){
        lcd.print(" ");
    }
}