컴공생 누르지 마세요! 컴공생 울어요.
[아두이노 실습] 초음파 센서와 PIR 센서를 이용한 자동화 경보 시스템 본문
틴커캐드에서 초음파 센서와 PIR 센서를 이용한 자동화 경보 시스템을 구현하는 실습을 진행하였습니다.
PIR 센서에서 움직임을 감지하면 LED 등이 켜지고, 초음파 센서에서 물체의 거리를 감지하여 LCD에 디스플레이합니다.
보드 & 센서 연결
다음과 같이 아두이노 보드, 브레드보드, 초음파 센서, PIR 센서, LCD, LED를 연결하였습니다.
소스코드
지난 글과 비교했을 때, loop()에서 PIR 센서에 움직임이 감지됐을 때 LED를 켜는 기능만 추가하였습니다.
#include <LiquidCrystal.h> // lcd 제어 라이브러리
LiquidCrystal lcd(12, 11, 7, 6, 5, 4); // lcd 핀 번호 설정
int distance = 0; // 거리 변수
// 초음파 거리 센서 읽기
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // 출력 모드로 설정
digitalWrite(triggerPin, LOW); // triggerPin 0V로 설정
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH); // triggerPin 5V로 설정
delayMicroseconds(10);
digitalWrite(triggerPin, LOW); // triggerPin 0V로 설정
pinMode(echoPin, INPUT); // 입력 모드로 설정
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH); // 펄스의 HIGH 구간 시간 측정
}
void setup()
{
lcd.begin(16, 2); // lcd 크기 (가로 16글자 x 세로 2줄)
lcd.print("distance = ");
pinMode(13, INPUT); // PIR 센서
pinMode(8, OUTPUT); // LED
Serial.begin(9600);
}
void loop()
{
Serial.println(digitalRead(8));
if(digitalRead(13)) // 물체 감지 시
{
digitalWrite(8, HIGH); // LED on
delay(5);
}
digitalWrite(8, LOW); // LED off
distance = 0.01723 * readUltrasonicDistance(3, 2);
lcd.setCursor(0, 1); // LCD의 2번째 줄로 커서 이동
lcd.print(distance); // 거리 출력
delay(10); // Delay a little bit to improve simulation performance
}
시뮬레이션
PIR 센서에서 움직임을 감지할 경우 LED가 잘은 보이지 않지만 희미하게 켜지는 걸 볼 수 있습니다.
또한, 초음파센서에서 거리를 감지하여 LCD에 디스플레이됨을 볼 수 있습니다.
'PROJECT > [임베디드] 아두이노 실습' 카테고리의 다른 글
[아두이노 실습] 초음파 센서로 거리를 측정하여 LCD에 출력하기 (0) | 2023.03.24 |
---|---|
[아두이노 실습] 3색 RGB LED 제어하기 (0) | 2023.03.24 |
Comments