---
# System prepended metadata

title: 專題五程式
tags: [code]

---

---
title: 專題五程式
tags: code
---

```c=
// 載入 Servo 函式庫的標頭檔
#include <Servo.h>

enum PinId {
    PinIdPontentiometerOutput = A0,
    PinIdServoMotorInput = 9,
};

enum PontentiometerOutputValue {
    PontentiometerOutputValueMin = 0,
    PontentiometerOutputValueMax = 1023,
};

enum ServoMotorInputAngle {
    ServoMotorInputAngleMin = 0,
    ServoMotorInputAngleMax = 179,
};

const int loopCycleDelayMilliseconds = 15;

// 宣告一個 Servo 的物件實體
Servo servoMotor;
int potentiometerValue;
int servoMotorAngle;

void setup() {
	// 告知伺服馬達所使用的腳位
  servoMotor.attach(PinIdServoMotorInput);
  Serial.begin(9600);
}

void loop() {
    // 讀取電位器數值
    potentiometerValue = analogRead(PinIdPontentiometerOutput);
    Serial.print("PontentiometerOutputPin: ");
    Serial.print(potentiometerValue);
    
    // 計算伺服馬達轉動角度：將電位器變化數值轉換為 0-180 度。
    servoMotorAngle = map(potentiometerValue, 
                          PontentiometerOutputValueMin, PontentiometerOutputValueMax, 
                          ServoMotorInputAngleMin, ServoMotorInputAngleMax);
    Serial.print(", angle: ");
    Serial.println(servoMotorAngle);
    
    // 轉動伺服馬達
    servoMotor.write(servoMotorAngle);
    
    delay(loopCycleDelayMilliseconds);
}
```