Arduino中LED灯实现256中颜色的渐变

根据颜色由三原色组成,根据其混成比例编写了此代码,实现了356种颜色的渐变过程;

//colort test;
const int red = 9;
const int green =10;
const int blue = 11;

void setup() {
  { 
    pinMode(red, OUTPUT); 
    pinMode(green, OUTPUT);  
    pinMode(blue, OUTPUT); 
  }
}

void loop() {
//总共有8*8*4=256种颜色;
 for(double r=0.125; r<=1.0; r+=0.125)   //8
   for(double g=0.125; g<=1.0; g+=0.125) //8
      for(double b=0.25; b<=1.0; b+=0.25) //4
      {
	    double k1=g/r;    //比例系数;
	    double k2=b/r;

		for(double number=1.0; number<=255.0; number+=1.0) //同比例增加;
		{
		  double R=number;
		  double G=k1*R;
		  double B=k2*R;

		  if( R>254 )        //判断增加的值是否大于最大值255,如果是则停止增加,慢慢变暗;否则继续增加;  
                  {
                    for( double R=255.0; R>0.0;R-=1.0)
		    {
                      if(R<=1.0)
                            break;
                      else
                      {
		          double G=k1*R;
		          double B=k2*R;

		          analogWrite(red,R);
		          analogWrite(green,G);
		          analogWrite(blue,B);
                          delay(20);
                      }
		    }
                    break;
                  }
                  

		  else if( G>254 )
                  {
                    for( double G=255.0; G>0.0;G-=1.0)
		    {
                        if(G<=1.0)
                           break;
                        else
                        {
  		            double R=G/k1;
		            double B=k2*R;
		            analogWrite(red,R);
		            analogWrite(green,G);
		            analogWrite(blue,B);
                            delay(20);
                        }
		    }
                    break;
                  }
                  
                  
                    else if( B > 254 )
                    {
                    for( double B=255.0; B>0.0;B-=1.0)
		    {
                        if(B<=1.0)
                              break;
                        else
                        {
  		          double R=B/k2;
		          double G=k1*R;

		          analogWrite(red,R);
		          analogWrite(green,G);
		          analogWrite(blue,B);
                          delay(20);
		         }
                      }
                      break;
                    }

                    else
		    {
		      analogWrite(red,R);
		      analogWrite(green,G);
		      analogWrite(blue,B);
                      delay(20);
		    }		
		} 
       }          
}
   

发布了250 篇原创文章 · 获赞 186 · 访问量 57万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览