Home Ask Login Register

Developers Planet

Your answer is one click away!

orglce February 2016

Array corrupts its characters C++

I'm writing a small program for the Arduino that is able to read RGB values from a char array of HEX color codes. Let me just give you an example because it is hard to explain differently:

From the arduino serial monitor I for example send this:


The first character tells the Arduino that this will be sequence of hex color codes. The second character tells it how many color codes there will be (it starts with 0. Thus 1 means two colors). Then the it loops trough six characters of every HEX code and adds it to the respected place in the hex[] char array. Hex[] array is two dimensional because in the first "dimension" it has the sequence number of a color and in the second it stores the RGB values of that color.

The output of this is following:

255 255 255 0 0 0 //the first part is okay, but the the second gets all messed up.

255 255 0 0 0 0 0 //the RED value of the next color gets set as the BLUE value of the previous color

And here is the code. I could't find any easier method for this idea to work. If you have suggestion on how to make this better or more efficient please let me know.

Thanks in advance!

char barva[10];
char hex[10][2];
long bluetoothVal;

bluetoothVal = Serial.read();    

if (bluetoothVal == '/')
        char load = input;
        int steps = load - '0';

        for (int counter = 0; counter <= steps; counter++)

            for (int i = 0; i <= 5; i++)

                char load = bluetoothVal;

                barva[i] = load;    

            long int rgb = strtol(barva,0,16); //=>rgb=0x001234FE;
            hex[counter][0] = (byte)(rgb>>16);


Rishikesh Raje February 2016

hex should be declared as

char hex[10][3];

You are accessing hex as hex[counter][2] = (byte)(rgb); at one place. For this you require a 10 * 3 array.

Post Status

Asked in February 2016
Viewed 2,418 times
Voted 12
Answered 1 times


Leave an answer

Quote of the day: live life