코풀 커뮤니티

터치센서/서보모터 - 터치하면 서보모터가 0-180도를 총 3번 반복하는 기능 구현하기

과제

윤*식

2025-01-03

코드에디터

언어 선택
#include <Servo.h> // Servo 라이브러리 포함

Servo myServo; // 서보모터 객체 생성
const int touchPin = 2; // 터치 센서 핀 번호
const int servoPin = 9; // 서보모터 핀 번호

void setup() {
pinMode(touchPin, INPUT); // 터치센서를 입력으로 설정
myServo.attach(servoPin); // 서보모터 핀 연결
myServo.write(0); // 서보모터를 0°로 초기화
Serial.begin(9600); // 시리얼 모니터 설정
}

void loop() {
int touchValue = digitalRead(touchPin); // 터치센서 값 읽기

if (touchValue == HIGH) { // 터치센서가 작동했을 때
Serial.println("Touch detected! Moving servo...");
for (int i = 0; i < 3; i++) { // 3번 반복
moveServo(); // 서보모터 이동 함수 호출
}
delay(500); // 반복이 끝난 후 잠시 대기
}
}

void moveServo() {
for (int angle = 0; angle <= 180; angle += 10) { // 0° -> 180°로 이동
myServo.write(angle);
delay(15); // 서보모터가 이동할 시간을 주기 위해 약간의 지연
}
for (int angle = 180; angle >= 0; angle -= 10) { // 180° -> 0°로 이동
myServo.write(angle);
delay(15);
}
}

입력
실행 결과
이 곳에 결과가 표시됩니다.
post-image
post-image
post-image
post-image
post-image
post-image
post-image
post-image
post-image
computerlogo