我正在使用rainbowduino,它有一些方法将单独的 r g b 值作为无符号字符,还有一些方法采用 24 位 rgb 颜色代码。
我想将 r g b 值转换为 uint32_t 类型的 24 位颜色代码(这样我的所有代码只需使用 r g b 值。
有什么想法吗?
我已经尝试过 uint32_t result = r << 16 + g << 8 + b; r = 100 g =200 b=0 呈现绿色,但 r=0 g=200 b=0 没有呈现任何内容
Rb.setPixelXY(unsigned char x, unsigned char y, unsigned char colorR, unsigned char colorG, unsigned char colorB)
This sets the pixel(x,y)by specifying each channel(color) with 8bit number.
Rb.setPixelXY(unsigned char x, unsigned char y, unit32_t colorRGB)
This sets the pixel(x,y)by specifying a 24bit RGB color code.
最佳答案
驱动程序代码是:
void Rainbowduino::setPixelXY(unsigned char x, unsigned char y, uint32_t colorRGB /*24-bit RGB Color*/)
{
if(x > 7 || y > 7)
{
// Do nothing.
// This check is used to avoid writing to out-of-bound pixels by graphics function.
// But this might slow down setting pixels (remove this check if fast disply is desired)
}
else
{
colorRGB = (colorRGB & 0x00FFFFFF);
frameBuffer[0][x][y]=(colorRGB & 0x0000FF); //channel Blue
colorRGB = (colorRGB >> 8);
frameBuffer[1][x][y]=(colorRGB & 0x0000FF); //channel Green
colorRGB = (colorRGB >> 8);
frameBuffer[2][x][y]=(colorRGB & 0x0000FF); //channel Red
}
}
所以我的想法与上面类似:
uint8_t x,y,r,b,g;
uint32_t result = (r << 16) | (g << 8) | b;
Rb.setPixelXY(x, y, result);
应该可以工作。我认为上面的内容可能需要括号,以确保正确的排序,因为“+”高于“<<”。也可能不会造成伤害,但“|”更好,以免防止不必要的进位。
附注请记住,当移位为无符号时,除非您想要算术移位而不是逻辑移位。 就这一点而言,我不喜欢轮类,因为轮类常常很困惑且效率低下。相反,联合既简单又高效。
union rgb {
uint32_t word;
uint8_t byte[3];
struct {
uint8_t blue;
uint8_t green;
uint8_t red;
} color ;
}rgb ;
// one way to assign by discrete names.
rbg.color.blue = b;
rbg.color.green = g;
rbg.color.red = r;
//or assign using array
rgb.byte[0] = b;
rgb.byte[1] = g;
rgb.byte[2] = r;
// then interchangeably use the whole integer word when desired.
Rb.setPixelXY(x, y, rgb.word);
不要搞乱跟踪类次。
关于Arduino 在 uint32_t 和无符号字符之间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15098129/