# 목적
- 초음파센서를 이용하여 가까운 곳에 물체가 감지되면 LED를 켜기
# 준비물
- 초음파센서, LED, 220옴저항
- 점퍼케이블, 아두이노, 브래드보드
# 입출력 설명
- 입력 : 초음파센서 값(아날로그 값, 0~1023)
- 처리 : 초음파센서에서 값을 읽어(analogRead), 값의 단위를 cm 단위로 변환하고, 일정 범위 안으로 물체가 감지되면 LED에 전기 주기(digitalWrite)
- 출력 : LED (디지털 값, 0 또는 1)
# 회로도
# 코드 (아두이노)
int trigPin = 2;
int echoPin = 3;
int ledPin = 13;
void setup() {
pinMode(echoPin, INPUT);
pinMode(trigPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
long duration, cm;
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin,LOW);
duration = pulseIn(echoPin,HIGH);
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
Serial.println();
if(cm < 8){
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
delay(100);
}
long microsecondsToCentimeters(long microseconds) {
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}