초음파 센서로 LED 제어하기

저번 시간에는 초음파란 무엇인지, 그리고 초음파 센서의 작동방식에 대해서 학습했다. 이번에는 초음파센서를 이용하여 LED를 ON/OFF하는 예제를 실습해보자.

아두이노 기초 프로그래밍에서, 조건문(if문)을 배웠는데, 조건문을 이용하여, 일정거리 이하일 때 LED를 ON하고, 일정거리 이상일 때 LED를 OFF하도록 해보자.

준비물

NO부품명수량
1아두이노 UNO R31
2초음파 센서(HC-SR04)1
3LED1
4330Ω 저항1
5브레드 보드1
6점퍼 케이블8

회로도

코드

코드 보기

int echoPin = 7; // 송신부
int trigPin = 8; // 수신부
 
int led = 3; // led핀을 선언
 
float duration;
float distance;

void setup() 
{
  Serial.begin(9600);
 
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
}
 
void loop() 
{
  digitalWrite(trigPin, HIGH); // 초음파 송신
  delay(10);
  digitalWrite(trigPin, LOW);
 
  duration = pulseIn(echoPin, HIGH); // Echo pin이 HIGH를 유지한 시간 저장
  distance = ((float)(340 * duration) / 10000) / 2; // 거리 계산
 
  // 측정된 거리 값를 시리얼 모니터에 출력
  Serial.print(distance);
  Serial.println("cm");
 
  // 측정된 거리가 10cm 이하라면, LED ON
  if (distance < 10) 
  {
    digitalWrite(led, HIGH);
  }
  // 측정된 거리가 10cm 이상이라면, LED OFF
  else 
{
    digitalWrite(led, LOW);
  }
  // 0.2초 동안 대기
  delay(200);
}

 

실습

6 Replies to “초음파 센서로 LED 제어하기”

  1. Attractive component to content. I just stumbled
    upon your site and in accession capital to say that I acquire in fact enjoyed account
    your weblog posts. Any way I’ll be subscribing in your augment or even I achievement
    you get admission to persistently quickly.

  2. We’re a group of volunteers and starting a brand new scheme in our community.
    Your site offered us with helpful info to work on. You’ve done an impressive activity and
    our entire neighborhood will likely be grateful to you.

  3. I just want to mention I am new to weblog and absolutely liked you’re web site. Most likely I’m likely to bookmark your site . You definitely come with terrific article content. Regards for sharing with us your web-site.

  4. I like the method that you write. Great website. Lovely understanding over listed here. Wonderful! Great Web page. I will certainly share this specific with all my friends! Thanks for your great blogs! I won’t be able to wait to confirm some those out! I love to write that type articles as if you.

Leave a Reply

Your email address will not be published. Required fields are marked *