carolinesabas
carolinesabas

Reputation: 3

How to change value in array and convert to RGB

I am making a project where RFID tags on 6 RFID readers will create a 6-digit HEX-code which will be converted and output through RGB.

I am converting HEX values to RGB values and print the values in serial, which works fine. E.g when I write #FFFFFF, Serial prints its respective RGB values - 255, 255, 255.

However, I want to be able to replace one of the letters in the HEX code at a time, which should change its RGB output in serial. In this example, I am attempting to replace the last letter of #FFFFFF to 3 - #FFFFF3. Serial still reads the first two values correctly, but does not convert the last value correctly.

I have read that it is better to create a new array with the new value - instead of replacing a value and changing the array but do not really know how. Here's what I have got now:

#include <stdlib.h>
#include <string.h>

void setup() {
Serial.begin(9600);
}

char hexColor[] = "#FFFFFF";
void HEXtoRGB();


void HEXtoRGB() {
hexColor[6] = "3";

char red[5] = {0};
char green[5] = {0};
char blue[5] = {0};

red[0] = green[0] = blue[0] = '0';
red[1] = green[1] = blue[1] = 'X';

red[2] = hexColor[1];
red[3] = hexColor[2];

green[2] = hexColor[3];
green[3] = hexColor[4];

blue[2] = hexColor[5];
blue[3] = hexColor[6];

long r = strtol(red, NULL, 16);
long g = strtol(green, NULL, 16);
long b = strtol(blue, NULL, 16);

Serial.println(r);
Serial.println(g);
Serial.println(b);
Serial.println(hexColor);
}

Any sort of input would be greatly appreciated, it's the first time writing in something else than javascript.

Thank you.

Upvotes: 0

Views: 203

Answers (2)

SiggiSv
SiggiSv

Reputation: 1229

The main error you're doing is confusing "3" with '3'.

"3" is a string which in C is a null-terminated array of chars while '3' is the character 3. So hexColor[6] = "3"; means: "write the memory address of the string "3" into hexColor[6]".

What you wanted to do is:

hexColor[6] = '3';

Upvotes: 2

Igor Staszewski
Igor Staszewski

Reputation: 401

This should work:

char hexColor[7] = "#FFFFFF";
int main(){
    for(int i=0; i<7; i++)
        printf("%c ", hexColor[i]);
    hexColor[6]='3';
    for(int i=0; i<7; i++)
        printf("%c ", hexColor[i]);
}

Outout: #FFFFFF #FFFFF3

Upvotes: 1

Related Questions