아래에 있는 아두이노 소스 코드를 활용해 봅시다.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <Servo.h>
const int trig_pin=11;
const int echo_pin=12;
const int servoPin=10;
Servo myservo;
int pushAngle = 10;
int currentAngle = 90;
void setup() {
myservo.attach(servoPin);
myservo.write(currentAngle);
delay(100);
myservo.detach();
pinMode(trig_pin, OUTPUT);
pinMode(echo_pin, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trig_pin,LOW);
delayMicroseconds(2);
digitalWrite(trig_pin,HIGH);
delayMicroseconds(10);
digitalWrite(trig_pin,LOW);
long duration=pulseIn(echo_pin,HIGH);
long distance=(duration/2)/29.1;
Serial.print(distance);
Serial.println("cm");
if (distance <= 10) {
myservo.attach(servoPin);
myservo.write(pushAngle);
delay(1000);
myservo.write(currentAngle);
delay(3000);
myservo.detach();
}
delay(100);
}
01:Servo헤더파일포함
02:초음파센서trigPin 11번 연결
03:초음파센서echoPin 12번 연결
04:t서보모터 servoPin 10번 연결
05:서보제어용 myservo객체 생성
06:첫번째 각도 10으로 설정
07:두번째 각도 90으로 설정
08:setup함수 정의
09:myservo attach 함수 호출로 10번핀 연결
10:myservo 각도 90도 동작
11:0.1초 대기
12:myservo 동작 종료
13:trig핀 출력모드 설정
14:echo핀 입력모드 설정
15:시리얼통신 9600 설정
16:loop 함수 정의
17:trigPin을 LOW로 설정(신호없음)
18:2마이크로초 대기
19:trigPin을 HIGH로 설정(신호있음)
20:10마이크로초 대기
21:trigPin을 LOW로 설정(신호없음)
22:echo HiGH구간 측정 후 duration에 저장
23:duration으로 distance값 계산하여 저장
24:시리얼모니터에 distance 값 출력
25:시리얼모니터에 "cm" 텍스트 출력
26:만약 distance가 10보다 작거나 같으면
27:myservo의 servoPin 10번 연결 후
28:myservo의 각도를 10도로 쓰기
29:1초 대기
30:myservo 각도를 90도로 쓰기
31:3초 대기
32:myservo 동작 종료