CODE 6.10 | 휨 센서로 서보 모터 제어하기
| 01 | #include <Servo.h> |
| 02 | |
| 03 | int flexPin = A0; // 휨 센서를 연결한 아날로그 핀 |
| 04 | int servoPin = 9; // 서보 모터를 연결한 디지털 핀 |
| 05 | |
| 06 | Servo myServo; // 서보 모터 객체 생성 |
| 07 | |
| 08 | void setup() { |
| 09 | myServo.attach(servoPin); // 서보 모터를 연결한 디지털 핀 설정 |
| 10 | Serial.begin(9600); // 시리얼 모니터 통신 시작 |
| 11 | } |
| 12 | |
| 13 | void loop() { |
| 14 | int flexValue = analogRead(flexPin); // 휨 센서 값 읽기 |
| 15 | |
| 16 | // 휨 센서 값(59~256)을 서보 모터 각도(0~180도)로 변환 |
| 17 | int angle = map(flexValue, 59, 256, 0, 180); |
| 18 | |
| 19 | // 변환된 각도를 0~180도 범위로 제한 |
| 20 | angle = constrain(angle, 0, 180); |
| 21 | |
| 22 | myServo.write(angle); // 서보 모터 각도 제어 |
| 23 | |
| 24 | Serial.print("Flex: "); |
| 25 | Serial.print(flexValue); |
| 26 | Serial.print(" -> Angle: "); |
| 27 | Serial.println(angle); |
| 28 | |
| 29 | delay(50); // 0.05초 대기 후 다시 측정 |
| 30 | } |
댓글 없음:
댓글 쓰기