Arduino在uint32_t和unsigned chars之间进行转换

时间:2013-02-26 19:58:53

标签: arduino rgb unsigned-char uint32-t

我正在使用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.

2 个答案:

答案 0 :(得分:4)

驱动程序代码为:

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

应该有效。我认为以上可能需要括号,以确保正确排序,因为“+”高于“&lt;&lt;”。也可能不会伤害但“|”更好,因为不是为了防止意外携带。

P.S。记住转换为无符号时,除非你想要算术移位而不是逻辑移位。 而且就此而言,我不喜欢轮班,因为他们经常搞砸并且效率低下。相反,联合是简单而有效的。

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

没有跟踪转变的情况。

答案 1 :(得分:0)

解决这个问题的一种方法是将位移到左边......

uint32_t result = r << 16 + g << 8 + b;