If you change str += String(buffer[i]);
to str += (char)buffer[i];
, it will print the ascii characters to the serial monitor.
The following sketch can be used to see the difference in binary compiled size using these two methods of "adding to the string".
// 4026 to 3758 bytes.
#define SIZE_BUFFER 18
#define MAX_SIZE_BLOCK 16
byte buffer[SIZE_BUFFER] = {
0x61, 0x73, 0x64, 0x61,
0x73, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20
};
String str = "";
void setup(){
Serial.begin(9600);
for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
{
// 4026 bytes. Prints: "97115100971153232323232323232323232"
//str += String(buffer[i]);
// 3758 bytes. Prints: "asdas "
str += (char)buffer[i];
}
Serial.println(" ");
Serial.println(str);
}
void loop(){}
Casting each element in the byte buffer to Char, then adding it to the string drops the binary compiled size from 4026 to 3758 bytes. This is good, but we can really improve the sketch by not using the String
object at all.
This sketch is the same as the first one, except it uses a Character Array
instead of a String
.
// 2074 bytes.
#define SIZE_BUFFER 18
#define MAX_SIZE_BLOCK 16
byte buffer[SIZE_BUFFER] = {
0x61, 0x73, 0x64, 0x61,
0x73, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20
};
// Use a char array instead of the String object.
char outputBuffer[SIZE_BUFFER];
void setup(){
Serial.begin(9600);
for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
{
// 2074 bytes. Prints: "asdas "
outputBuffer[i] = (char)buffer[i];
}
Serial.println(" ");
Serial.println(outputBuffer);
}
void loop(){}
The binary compiled size is 2074 bytes. That's 1684 bytes less than using the String
object.
There are many functions available to work with Character Arrays
on an Arduino, such as http://www.cplusplus.com/reference/cstring/ and http://www.cplusplus.com/reference/cstdlib/.