---
# System prepended metadata

title: 0521 用
tags: [code]

---

---
title: 0521 用
tags: code
---

```c++
enum digitalOutput {
	LedRed = 11,
	LedGreen = 10,
	LedBlue = 9,
};

// 類比輸入腳位
enum analogInput {
	AiRed = A0,
	AiGreen = A1,
	AiBlue = A2,
};

// 正規化後(0-255)輸出至 PWM 的對應 RGB 數值
int outputRedValue = 0;
int outputGreenValue = 0;
int outputBlueValue = 0;

// 類比輸入的 RGB 大小相對讀值(0-1024)
int inputRedValue = 0;
int inputGreenValue = 0;
int inputBlueValue = 0;

void setup() {
	// 設定串列埠傳輸速率，單位：鮑率(Baud rate)
	Serial.begin(9600);

  // 設定數位輸出對應腳位
	pinMode(LedRed, OUTPUT);
	pinMode(LedGreen, OUTPUT);
	pinMode(LedBlue, OUTPUT);
}

void loop() {
	// 透過類比輸入從光敏電阻電路讀取電壓值
  inputRedValue = analogRead(AiRed);
  delay(5);
  inputGreenValue = analogRead(AiGreen);
  delay(5);
  inputBlueValue = analogRead(AiBlue);

	// 將輸入(0-1024)正規化成 PWM 值(0-255)
	outputRedValue = inputRedValue / 4;
	outputGreenValue = inputGreenValue / 4;
	outputBlueValue = inputBlueValue / 4;

	// 將 PWM 值輸出至對應 RGB LED 腳位
	analogWrite(LedRed, outputRedValue);
	analogWrite(LedGreen, outputGreenValue);
	analogWrite(LedBlue, outputBlueValue);

	// 顯示數值在串列監視器
	Serial.print("Input: ");
	Serial.print("R: ");
	Serial.print(inputRedValue);
	Serial.print(", G: ");
	Serial.print(inputGreenValue);
	Serial.print(", B: ");
	Serial.print(inputBlueValue);
	Serial.print(" # ");
	Serial.print("Output: ");
	Serial.print("R: ");
	Serial.print(outputRedValue);
	Serial.print(", G: ");
	Serial.print(outputGreenValue);
	Serial.print(", B: ");
	Serial.print(outputBlueValue);
	Serial.println("\n");
}
```