ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 아두이노 초음파 센서 (Wave)
    Arduino 2019. 8. 28. 12:22

    //초음파 센서 거리 확인
    int tPin = 2;
    int ePin = 3;
    void setup() {
      Serial.begin(9600);
      pinMode(tPin,OUTPUT);
      pinMode(ePin,INPUT);
    }

    void loop() {
      long d1,d2;
      //초음파를 발생하기 위해 트리거 펄스를 만드는 부분
      //trigPin으로 지정된 아두이노 핀을 10[us:마이크로초]의 High 펄스를 만든다.
      digitalWrite(tPin, LOW);
      //delayMicroseconds : us(마이크로초) 단위로 멈추는 함수
      //1,000,000us = 1sec
      delayMicroseconds(2);
      digitalWrite(tPin,HIGH);
      delayMicroseconds(10);
      digitalWrite(tPin,LOW);

      //pulseIn : 디지털 핀 번호, 시작 상태 값을 넣어주면 아두이노는 상태가
      //          바뀔 때까지 기다리고 상태가 바뀌면 흐른 시간을 us 단위로 알려줌
      d1 = pulseIn(ePin, HIGH);

      /*
       * 속력 구하기
       * 340 * 100(cm)/1,000,000(us) / 2(왕복)
       * 0.034 /2
       * 0.017
       * 17 / 1,000,000(us)
       */
      //거리(cm) = 시간(us) * 속력((340m/s)/2(왕복)) -> 음속:340ms
      d2 = d1 * 17 / 1000;

      Serial.print("Distance : ");
      Serial.print(d2);
      Serial.println("cm");
      delay(100);

    }

    댓글

Designed by Tistory.