Created
January 11, 2018 20:09
-
-
Save abachman/5257b1700cc77a6ebabdff1aeefb3376 to your computer and use it in GitHub Desktop.
Arduino / C++ simple array split join
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Simple example of string join and split functions for arrays of uint8_t | |
* values of known length. | |
* | |
* Output: | |
------------------ | |
array split / join | |
------------------ | |
SENDING >> 52 225 210 170 219 | |
RECEIVING << 52 225 210 170 219 | |
---- | |
SENDING >> 56 6 40 252 154 | |
RECEIVING << 56 6 40 252 154 | |
---- | |
SENDING >> 139 77 7 114 117 | |
RECEIVING << 139 77 7 114 117 | |
---- | |
*/ | |
String join(uint8_t vals[], char sep, int items) { | |
String out = ""; | |
for (int i=0; i<items; i++) { | |
out = out + String(vals[i]); | |
if ((i + 1) < items) { | |
out = out + sep; | |
} | |
} | |
return out; | |
} | |
void split(String value, char sep, uint8_t vals[], int items) { | |
int count = 0; | |
char *val = strtok((char *)value.c_str(), &sep); | |
while (val != NULL && count < items) { | |
vals[count++] = (uint8_t)atoi(val); | |
val = strtok(NULL, &sep); | |
} | |
} | |
uint8_t send_array[5]; | |
uint8_t receive_array[5]; | |
void setup() { | |
Serial.begin(115200); | |
while (! Serial); | |
Serial.println(F("------------------")); | |
Serial.println(F("array split / join")); | |
Serial.println(F("------------------")); | |
} | |
void loop() { | |
// put your main code here, to run repeatedly: | |
for (int i=0; i<5; i++) { | |
send_array[i] = random(255); | |
} | |
String s_rep = join(send_array, ' ', 5); | |
Serial.print("SENDING >> "); | |
Serial.println(s_rep); | |
split(s_rep, ' ', receive_array, 5); | |
Serial.print("RECEIVING << "); | |
for (int i=0; i<5; i++) { | |
Serial.print(receive_array[i]); | |
Serial.print(" "); | |
} | |
Serial.println(); | |
Serial.println("----"); | |
delay(5000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment