Arduino RGB 颜色渐变代码(附上C语言版本)

这段代码来自
Smooth RGB LED Transitions with Johnny-Five - Arduino Project Hub

const int redPin = 11;
const int greenPin = 10;
const int bluePin = 9;
void setup() {
 // Start off with the LED off.
 setColourRgb(0,0,0);
}
void loop() {
 unsigned int rgbColour[3];
 // Start off with red.
 rgbColour[0] = 255;
 rgbColour[1] = 0;
 rgbColour[2] = 0;  
 // Choose the colours to increment and decrement.
 for (int decColour = 0; decColour < 3; decColour += 1) {
   int incColour = decColour == 2 ? 0 : decColour + 1;
   // cross-fade the two colours.
   for(int i = 0; i < 255; i += 1) {
     rgbColour[decColour] -= 1;
     rgbColour[incColour] += 1;
     setColourRgb(rgbColour[0], rgbColour[1], rgbColour[2]);
     delay(5);
   }
 }
}
void setColourRgb(unsigned int red, unsigned int green, unsigned int blue) {
 analogWrite(redPin, red);
 analogWrite(greenPin, green);
 analogWrite(bluePin, blue);
}

在嵌入式空间紧张的情况下,如果使用HSV颜色转换为RGB,会引入数学库的一些函数,导致固件会明显增大。所以直接使用RGB控制颜色会显著减小固件体积。

C语言版本如下,C语言本例PWM范围是0-999:

void light_set_rgb(uint32_t R, uint32_t G, uint32_t B)
{
	light_pwm_set_duty (COLOR_LIGHT_R_PWM_NAME,R);
	light_pwm_set_duty (COLOR_LIGHT_G_PWM_NAME,G);
	light_pwm_set_duty (COLOR_LIGHT_B_PWM_NAME,B);
}

void smooth_changing_color_light()
{
	 uint32_t rgbColour[3];
	 // Start off with red.
	 rgbColour[0] = 999;
	 rgbColour[1] = 0;
	 rgbColour[2] = 0;
	 // Choose the colours to increment and decrement.
	 for (int decColour = 0; decColour < 3; decColour += 1) {
		   int incColour = decColour == 2 ? 0 : decColour + 1;
		   // cross-fade the two colours.
		   for(int i = 0; i < 1000; i += 1) {
			 rgbColour[decColour] -= 1;
			 rgbColour[incColour] += 1;
			 light_set_rgb(rgbColour[0], rgbColour[1], rgbColour[2]);
			 delay(2);
		   }
	 	 }
}
  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值