脈衝寬度調變(PWM, Pulse Width Modulation)

功能:

  1. 馬達調速
  2. 燈光亮度調整

PWM是將原本一個完整的供電週期,分割成256格(0~255),藉由指定PWM值產生一定比例的供電時間造成給予的能量/電量在0%到100%間。簡單說,就是以非常快速的方式切換送電/關電的過程,一如騎車催油門,可以用催/收油門的方式來控制引擎給油。

詳細說明請參考: 脈衝寬度調變

控制LED不同程度的亮暗

/Controlling the brightness of a LED
int LED = 3;
void setup() {
  pinMode(LED, OUTPUT);
}

void loop() {
  analogWrite(LED, 255);
  delay(500);
  analogWrite(LED, 192);
  delay(500);
  analogWrite(LED, 128);
  delay(500);
  analogWrite(LED, 64);
  delay(500); 
  analogWrite(LED, 0);
  delay(500);
}

使用迴圈方式:

```c
/Controlling the brightness of a LED
int LED = 3;
void setup() {
  pinMode(LED, OUTPUT);
}

void loop() {
  int diff = 32; //亮暗間隔數值
  int i;
  for (i = 255; i > 0; i -= diff){
    analogWrite(LED, i);
    delay(500);
  }
}

注意:Arduino中的數位腳只有 3, 5, 6, 9, 10, 和 11腳提供8位元的PWM輸出,使用analogWrite()函式。