[따라하기] 아두이노 기초 – 초음파센서 사용하기 by ODIY 한국과학창의재단

[따라하기] 아두이노 기초 – 초음파센서 사용하기 by ODIY 한국과학창의재단

 

 

Ardunio – Ultrasound sensor with LED

 

 

 

 

 

#define TRIG 2  // Sending out ultrasound
#define ECHO 3  // Receiving ultrasound
#define LED 9   // Controlling LED

void setup() {
  // put your setup code here, to run once:
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(TRIG, LOW);  // Turn off ultrasound
  delayMicroseconds(2);     
  digitalWrite(TRIG, HIGH); // Turn on ultrasound
  delayMicroseconds(2);
  digitalWrite(TRIG, LOW);

  long distance = pulseIn(ECHO, HIGH)/58.2; // Calculate distance by CM (58.2)

  analogWrite(LED, map(distance, 0, 30, 0, 150));
  //delay(100);
}