确实可以在不同颜色之间褪色。我在 Arduino 书籍和网络上的代码中通常也缺少的是,可以在 Arduino IDE 中编写 C++ 类。因此,我将展示一个使用 C++ 类在颜色之间渐变的示例。
应该解决的一个问题是应该对哪些引脚进行模拟写入,因为并非所有引脚都能够进行脉冲宽度调制 ( PWM )。在 Arduino 设备上,支持 PWM 的引脚用波浪号“~”表示。Arduino UNO 有数字引脚 ~3、~5、~6、~9、~10 和 ~11。大多数 Arduino 将这些引脚用于 PWM,但请检查您的设备以确保。您可以通过将 LED 打开 1 毫秒和 1 毫秒来在常规数字引脚上创建 PWM,这模拟了 LED 上 50% 的功率。或者将其打开 3 毫秒和 1 毫秒,这模拟了 75% 的功率。
为了使 LED 变暗,您必须减少/增加 PWM 值并稍等片刻。您将不得不等待一会儿,否则 arduino 会每秒尝试使 LED 褪色/变暗数千次,而您将看不到褪色效果,尽管它可能在那里。因此,您正在寻找一种方法来逐渐减少/增加第二个参数以analogWrite( )
用于三个 LED;有关更详尽的解释,请参见Arduino Cookbook的第 7 章。无论如何,这本书对于 Arduino 粉丝来说都是一本好书!
所以我修改了 OP 的代码以包含一个“rgb_color”类,它或多或少只是一个红色、绿色和蓝色值的容器。但更重要的是推子类。构造推子实例时,正确的引脚应分别位于构造函数中的红色、绿色和蓝色。推子包含一个成员函数void fade( const rgb_color& const rgb_color&)
,它将在输入和输出颜色之间进行渐变。默认情况下,该函数从输入颜色到输出颜色需要 10 毫秒的 256 步。(请注意,由于整数除法,这并不意味着每一步都是 1/256 th,但从感知上讲你不会注意到它)。
/*
* LedBrightness sketch
* controls the brightness of LEDs on "analog" (PWM) output ports.
*/
class rgb_color {
private:
int my_r;
int my_g;
int my_b;
public:
rgb_color (int red, int green, int blue)
:
my_r(red),
my_g(green),
my_b(blue)
{
}
int r() const {return my_r;}
int b() const {return my_b;}
int g() const {return my_g;}
};
/*instances of fader can fade between two colors*/
class fader {
private:
int r_pin;
int g_pin;
int b_pin;
public:
/* construct the fader for the pins to manipulate.
* make sure these are pins that support Pulse
* width modulation (PWM), these are the digital pins
* denoted with a tilde(~) common are ~3, ~5, ~6, ~9, ~10
* and ~11 but check this on your type of arduino.
*/
fader( int red_pin, int green_pin, int blue_pin)
:
r_pin(red_pin),
g_pin(green_pin),
b_pin(blue_pin)
{
}
/*fade from rgb_in to rgb_out*/
void fade( const rgb_color& in,
const rgb_color& out,
unsigned n_steps = 256, //default take 256 steps
unsigned time = 10) //wait 10 ms per step
{
int red_diff = out.r() - in.r();
int green_diff = out.g() - in.g();
int blue_diff = out.b() - in.b();
for ( unsigned i = 0; i < n_steps; ++i){
/* output is the color that is actually written to the pins
* and output nicely fades from in to out.
*/
rgb_color output ( in.r() + i * red_diff / n_steps,
in.g() + i * green_diff / n_steps,
in.b() + i * blue_diff/ n_steps);
/*put the analog pins to the proper output.*/
analogWrite( r_pin, output.r() );
analogWrite( g_pin, output.g() );
analogWrite( b_pin, output.b() );
delay(time);
}
}
};
void setup()
{
//pins driven by analogWrite do not need to be declared as outputs
}
void loop()
{
fader f (3, 5, 6); //note OP uses 9 10 and 11
/*colors*/
rgb_color yellow( 250, 105, 0 );
rgb_color orange( 250, 40, 0 );
rgb_color red ( 255, 0, 0 );
rgb_color blue ( 10, 10, 255 );
rgb_color pink ( 255, 0, 100 );
rgb_color purple( 200, 0, 255 );
rgb_color green ( 0, 255, 0 );
rgb_color white ( 255, 255, 255 );
/*fade colors*/
f.fade( white, yellow);
f.fade( yellow, orange);
f.fade( orange, red);
f.fade( red, blue);
f.fade( blue, pink);
f.fade( pink, purple);
f.fade( purple, green);
f.fade( green, white);
}