초음파 센서 코드
스크롤을 내리면서 초음파 센서 코드를
확인하고, 내려받기 버튼을 클릭해 주세요.
내려받은 코드를 실행하는 방법을 알아봅시다.
코드 실행 방법 안내 버튼을 클릭해 주세요.
const int trigPin = 2;
// 초음파 센서의 Trig 핀과 마이크로컨트롤러 보드의 2번 핀을 연결
const int echoPin = 3;
// 초음파 센서의 Echo 핀과 마이크로컨트롤러 보드의 3번 핀을 연결
const int motorPin1 = 6;
// 모터 드라이버 모듈의 1A 핀과 마이크로컨트롤러 보드의 6번 핀을
연결
const int motorPin2 = 7;
// 모터 드라이버 모듈의 1B 핀과 마이크로컨트롤러 보드의 7번 핀을
연결
void setup() { // 시리얼 통신을 초기화
Serial.begin(9600);
// 컴퓨터와의 시리얼 통신을 9600 bps로 초기화
pinMode(trigPin, OUTPUT); // Trig 핀을 출력으로 설정
pinMode(echoPin, INPUT); // Echo 핀을 입력으로 설정
pinMode(motorPin1, OUTPUT);
// 모터를 제어하기 위해 모터 드라이버 모듈의 1A 핀을 출력으로
설정
pinMode(motorPin2, OUTPUT);
// 모터를 제어하기 위해 모터 드라이버 모듈의 1B 핀을 출력으로
설정
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
}
void loop() {
long duration = measureDistance();
// 초음파 센서를 통해 거리를 측정하는 함수 호출
Serial.print("Distance: ");
// 측정한 거리를 시리얼 모니터에 출력
Serial.print(duration);
Serial.println(" cm");
// 측정한 거리를 시리얼 모니터에 cm 단위로 출력
if (duration <= 20 && duration != -1) {
// 거리가 유효하면서 20 cm 이하인 경우 모터가 작동함.
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
} else {
// 거리가 유효하지 않거나 20 cm 이상인 경우 모터가 정지함.
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
}
delay(1000); // 1 초 대기
}
long measureDistance() {
digitalWrite(trigPin, LOW); // 초음파 발생 초기화
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
// Echo 핀으로부터 초음파 수신 시간 측정
long distance = duration * 0.034 / 2; // 거리 계산
if (distance == 0 || distance >= 400) {
// 거리가 유효하지 않은 경우 대체 값을 사용
distance = -1; // 대체 값 -1로 설정
}
return distance; // 거리 계산 반복
}