跳到主要内容

Lesson 8: Brightness with PWM

English

Half on

  • analogWrite(9, 128); makes pin 9 switch on and off very fast: on about half of the time.
  • This is called PWM. An LED looks half as bright.
  • The number goes from 0 (always off) to 255 (always on).
  • Only pins with a ~ on the board can do this: 3, 5, 6, 9, 10 and 11.
void setup() {
  pinMode(9, OUTPUT);
}

void loop() {
  for (int b = 0; b <= 255; b = b + 5) {    // slowly brighter
    analogWrite(9, b);
    delay(20);
  }
  for (int b = 255; b >= 0; b = b - 5) {    // slowly darker
    analogWrite(9, b);
    delay(20);
  }
}

登录或创建账户

IGCSE, A-Level & AP