RGB彩灯–彩虹颜色渐变

按照RGB彩灯里面的线路连接好后,更改代码,使灯的颜色按照彩虹颜色过渡。实现的代码如下:

int x = 0;
int y = 0;
int z = 0;

int redPin = 11;
int greenPin = 10;
int bluePin = 9;

void setup()
{

	pinMode(redPin, OUTPUT);
	pinMode(greenPin, OUTPUT);
	pinMode(bluePin, OUTPUT);
	digitalWrite(redPin, 0);
	digitalWrite(greenPin, 0);
	digitalWrite(bluePin, 0);
	Serial.begin(9600);
}

void loop()
{
	for (x = 0; x < 256; x++)
	{
		y = 0;
		z = 0;
		analogWrite(redPin, 255 - x);
		analogWrite(greenPin, 255 - y);
		analogWrite(bluePin, 255 - z);
		delay(10);
	}
	for (y = 0; y < 256; y++) { x = 255; z = 0; analogWrite(redPin, 255 - x); analogWrite(greenPin, 255 - y); analogWrite(bluePin, 255 - z); delay(10); } for (x = 255; x > 0; x--)
	{
		y = 255;
		z = 0;
		analogWrite(redPin, 255 - x);
		analogWrite(greenPin, 255 - y);
		analogWrite(bluePin, 255 - z);
		delay(10);
	}
	for (z = 0; z < 256; z++) { x = 0; y = 255; analogWrite(redPin, 255 - x); analogWrite(greenPin, 255 - y); analogWrite(bluePin, 255 - z); delay(10); } for (y = 255; y > 0; y--)
	{
		x = 0; 
		z= 255;
		analogWrite(redPin, 255 - x);
		analogWrite(greenPin, 255 - y);
		analogWrite(bluePin, 255 - z);
		delay(10);
	}
	for (x = 0; x < 256;x++) { y = 0; z = 255; analogWrite(redPin, 255 - x); analogWrite(greenPin, 255 - y); analogWrite(bluePin, 255 - z); delay(10); } for (z = 255; z > 0;z--)
	{
		y = 0;
		x = 255;
		analogWrite(redPin, 255 - x);
		analogWrite(greenPin, 255 - y);
		analogWrite(bluePin, 255 - z);
		delay(10);

	}
}

这里的代码需要解释的就是

analogWrite(redPin, 255 - x);
analogWrite(greenPin, 255 - y);
analogWrite(bluePin, 255 - z);

因为我们采用的是共阳的RGB彩灯。共阳RGB就是把正极拉到一个公共引脚,其他三个端则是负极。外表上共阳和共阴RGB彩灯没有区别,然而在使用上是有区别的,区别分为以下两点:

(1)接线中的改变,共阳的话,共用端需要接5V,而不是GND,否则LED不能被点亮。

(2)第二点就是,在颜色的调配上,与共阴是完全相反的。

举个例子:共阴RGB显示红色为R-255,G-0,B-0。然而共阳则完全相反,RGB数值是R-0,G-255,B-255。
0 Comments
Leave a Reply