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);
		   }
	 	 }
}

你可能感兴趣的:(#,Arduino,#,C语言,Arduino,颜色渐变,RGB)