Hello everyone!
First of all, I'm sorry for my English!
I'm trying:
- storing strings (char arrays) in flash memory
- read and store these strings in the same buffer always (another array char);
- concatenate this buffer and another of these strings;
- print this buffer, after all this process, on the serial monitor.
The storage of strings in the buffer and the concatenations are done through a lib I wrote.
This is my code:
#include <MyString.h>
MyString string;
const char STR_0[] PROGMEM = "string0_";
const char STR_1[] PROGMEM = "string1_";
const char STR_2[] PROGMEM = "string2_";
const char STR_3[] PROGMEM = "string3_";
const char STR_4[] PROGMEM = "string4_";
const char STR_5[] PROGMEM = "string5_";
const char* const STR[] PROGMEM = {
STR_0,
STR_1,
STR_2,
STR_3,
STR_4,
STR_5
};
char buff[17];
void function() {
/*
string.put_P(buff, STR[0]);
string.catenate_P(buff, STR[1]);
Serial.println(buff);
string.put_P(buff, STR[1]);
string.catenate_P(buff, STR[2]);
Serial.println(buff);
string.put_P(buff, STR[2]);
string.catenate_P(buff, STR[3]);
Serial.println(buff);
string.put_P(buff, STR[3]);
string.catenate_P(buff, STR[4]);
Serial.println(buff);
string.put_P(buff, STR[4]);
string.catenate_P(buff, STR[5]);
Serial.println(buff);
Serial.println();
*/
byte lastSTR = (sizeof(STR) / sizeof(char *)) - 1;
for(byte i = 0; i < lastSTR; i++) {
string.put_P(buff, STR[i]);
string.catenate_P(buff, STR[i + 1]);
Serial.println(buff);
}
Serial.println();
}
void setup() {
Serial.begin(9600);
}
void loop() {
function();
}
The lines that are commented on seem to work fine. Just below, I tried to optimize the code with a for loop, but the result on the serial monitor is 2 or 3 random characters!
The functions of my lib I am using are these:
void MyString :: put_P(char *buffer, const char *str) {
byte i; // counter;
for(i = 0; pgm_read_byte(str + i); i++) buffer[i] = pgm_read_byte(str + i);
buffer[i] = '\0';
}
void MyString :: catenate_P(char *str0, const char *str1) {
byte i, j; // counters;
for(i = 0; str0[i]; i++); // identifies the end of str0;
for(j = 0; pgm_read_byte(str1 + j); j++) str0[i + j] = pgm_read_byte(str1 + j);
str0[i + j] = '\0';
}
Why does the commented code work and the for loop does not?
Thank you in advance for your attention