做完了 Blink,再做一个 Fade,就是通常所说的呼吸灯。因为要用到 PWM 输出功能,所以,LED 要从 D8 换到 D9,因为Arduino UNO 具备 PWM 功能的管脚位于:D3,D5,D6,D9,D10,D11。
实验过程是这样:通过一个外接到 A0 脚的电位器调节连接到 D9 脚的 LED 的亮度。
Arduino 代码是这样:
/*
Fade
This example shows how to fade an LED on pin 9 using the analogWrite()
function through a potentiometer connected to A0.
The analogWrite() function uses PWM, so if you want to change the pin you're
using, be sure to use another PWM capable pin. On most Arduino, the PWM pins
are identified with a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
*/
const int led = 9; // the PWM pin the LED is attached to
const int pot = A0; // the ADC0 channel connected to potentiometer
int brightness = 0; // how bright the LED is
int fadeAmount = 0; // how many points to fade the LED by potentiometer
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
pinMode(pot, INPUT);
// for debugging:
Serial.begin(115200);
}
// the loop routine runs over and over again forever:
void loop() {
// read the potentiometer from A0:
fadeAmount = analogRead(pot);
// map the value from 0-1023 to 0-255:
brightness = map(fadeAmount, 0, 1023, 0, 255);
// set the brightness of pin 9:
analogWrite(led, brightness);
// show the PWM value on Serial Monitor:
Serial.print("Current PWM: ");
Serial.println(brightness);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
|