Reputation:
Im having an issue making a mastermind game on Arduino. I have 4 rgb leds that each have names for their pins (red1, green1, blue1, red2, green2, blue2, etc.)
Now my issue is when I entered 4 colors to compare to the colors that the Arduino chose in the beginning of the game. The code is too repetitive, and since Im still learning Arduino I was wondering if there is a solution to this.
Here is the part of my code that assignes colors to the leds with the chosen color (colorcode 1 = green, 2 = red, etc.)
void Convertmycolor()
{
if (colorpicker1 == 1)
{
red1 = 0;
green1 = 255;
blue1 = 255;
}
else if (colorpicker1 == 2)
{
red1 = 0;
green1 = 0;
blue1 = 255;
}
else if (colorpicker1 == 3)
{
red1 = 255;
green1 = 255;
blue1 = 0;
}
else if (colorpicker1 == 4)
{
red1 = 255;
green1 = 0;
blue1 = 0;
}
else if (colorpicker1 == 5)
{
red1 = 255;
green1 = 255;
blue1 = 255;
}
if (colorpicker2 == 1)
{
red2 = 0;
green2 = 255;
blue2 = 255;
}
else if (colorpicker2 == 2)
{
red2 = 0;
green2 = 0;
blue2 = 255;
}
else if (colorpicker2 == 3)
{
red2 = 255;
green2 = 255;
blue2 = 0;
}
else if (colorpicker2 == 4)
{
red2 = 255;
green2 = 0;
blue2 = 0;
}
else if (colorpicker2 == 5)
{
red2 = 255;
green2 = 255;
blue2 = 255;
}
if (colorpicker3 == 1)
{
red3 = 0;
green3 = 255;
blue3 = 255;
}
else if (colorpicker3 == 2)
{
red3 = 0;
green3 = 0;
blue3 = 255;
}
else if (colorpicker3 == 3)
{
red3 = 255;
green3 = 255;
blue3 = 0;
}
else if (colorpicker3 == 4)
{
red3 = 255;
green3 = 0;
blue3 = 0;
}
else if (colorpicker3 == 5)
{
red3 = 255;
green3 = 255;
blue3 = 255;
}
if (colorpicker4 == 1)
{
red4 = 0;
green4 = 255;
blue4 = 255;
}
else if (colorpicker4 == 2)
{
red4 = 0;
green4 = 0;
blue4 = 255;
}
else if (colorpicker4 == 3)
{
red4 = 255;
green4 = 255;
blue4 = 0;
}
else if (colorpicker4 == 4)
{
red4 = 255;
green4 = 0;
blue4 = 0;
}
else if (colorpicker4 == 5)
{
red4 = 255;
green4 = 255;
blue4 = 255;
}
}
As you can see its very repetitive and I want it to be shorter. I tried googling but didnt see anything that could help me in this situation (or im bad at searching)
Hopefully you can help me with this. Thanks.
Upvotes: 0
Views: 41
Reputation: 45443
You can use array index to map your values eg like this :
#define COLOR_LENGTH 4
#define PICKER_LENGTH 4
struct Color {
uint8_t r, g, b;
};
const Color colorTable[] = {
{0, 255, 255},
{0, 0, 255},
{255, 255, 0},
{255, 0, 0},
{255, 255, 255}
};
uint8_t colorPickers[PICKER_LENGTH];
Color colors[COLOR_LENGTH];
And converting is just mapping the colors to the right index :
//set the pickers
colorPickers[0] = 3;
colorPickers[1] = 1;
colorPickers[2] = 4;
colorPickers[3] = 5;
//set colors according to table
for (uint8_t i = 0; i < COLOR_LENGTH; i++) {
colors[i] = colorTable[colorPickers[i] - 1];
}
Upvotes: 1