Note: I couldn't find any answer to this problem except for turning the char array into a string and converting it into a int, but I've been told that using Strings is not very good.
So what i want to do is get a char array color which has the value of "#fedcba " or something, and turn it into three ints of values 254, 220, and 186 (0xfe, 0xdc, & 0xba in decimal). how do I do it? I'm not giving any code samples because of how little I've found to do except try using atoi(), which dosen't work.
MorganS
January 25, 2018, 4:19am
#3
char arrayToConvert[] = "#fedcba";
byte convertTwoBytes(char arrayToConvert[]) {
//take two Hex characters at the provided address and return the byte value
//Must check that characters are valid hex before passing to this function
byte temp = 0;
if(arrayToConvert[0]>='0' && arrayToConvert[0]<='9') temp = arrayToConvert[0] - '0';
if(arrayToConvert[0]>='A' && arrayToConvert[0]<='F') temp = arrayToConvert[0] - 'A' + 10;
if(arrayToConvert[0]>='a' && arrayToConvert[0]<='f') temp = arrayToConvert[0] - 'a' + 10;
temp *= 0x10;
if(arrayToConvert[1]>='0' && arrayToConvert[1]<='9') temp += arrayToConvert[1] - '0';
if(arrayToConvert[1]>='A' && arrayToConvert[1]<='F') temp += arrayToConvert[1] - 'A' + 10;
if(arrayToConvert[1]>='a' && arrayToConvert[1]<='f') temp += arrayToConvert[1] - 'a' + 10;
return temp;
}
bool convertRGB(char arrayToConvert[], byte &R, byte &G, byte &B) {
//return false if the provided array could not be converted, true if valid values put into R, G and B.
if(arrayToConvert[0] != '#') return false;
if(strlen(arrayToConvert) != 7) return false;
for(byte i=1; i<7; i++) {
//note this relies on certain properties of the ASCII characters: 0-9 occurs before A-Z occurs before a-z
if(arrayToConvert[i] < '0') return false;
if(arrayToConvert[i] > '9' && arrayToConvert[i] < 'A') return false;
if(arrayToConvert[i] > 'F' && arrayToConvert[i] < 'a') return false;
if(arrayToConvert[i] > 'f') return false;
}
R = convertTwoBytes(&arrayToConvert[1]);
G = convertTwoBytes(&arrayToConvert[3]);
B = convertTwoBytes(&arrayToConvert[5]);
return true;
}
void setup() {
Serial.begin(9600);
Serial.println("Test RGB converter...");
byte R, G, B;
if(convertRGB(arrayToConvert, R, G, B)) {
Serial.print("R = ");
Serial.println(R);
Serial.print("G = ");
Serial.println(G);
Serial.print("B = ");
Serial.println(B);
} else {
Serial.println("Conversion failed");
}
}
void loop() {
//empty
}
It worked really well, I just removed ~40 lines of code from my old way of getting input 3 times!