Hello,
I'm pretty new to writing libraries for Arduino. Reason I'm writing a library is because my code is getting messy and too long. I was using Strings before in my code, but since I read a lot of things to not use these, because of memory issues, heap fragmentation etc I stopped using them (my ESP8266 also kept overflowing over and over..).
So long story short I am writing a class in the library that needs to do a lot of data parsing, concentating, finding certain key words etc. However I have not been able to get far because of the many many issues I ran into using char arrays in a library. To start of I can't declare it in my header file, since that will give an error. Not too much of a problem since I can move it to a set/get public function. However when I try to modify the data to something useful I keep running into overflows, errors and issues. My question is, how should I do this properly, and safe (memory-wise)?
Here an example of the class .h file (I editted the class a little bit to rename sensitive vars and remove some unused/unrelevant stuff):
#ifndef Test_h
#define Test_h
#ifndef stdlib_h
#include <stdlib.h>
#endif
class Test
{
public:
Test(int ID);
char *request_msg(void);
void process_msg(char *payload);
int ID = 0;
int a = 1500;
int b = 1500;
}
#endif
Here the .cpp file:
#include "Test.h"
#ifndef stdio_h
#include <stdio.h>
#endif
#ifndef string_h
#include <string.h>
#endif
Test::Test(int ID)
{
// initialize this instance's variables
this->ID = ID;
}
char* Test::request_msg(void)
{
char buffer[25];
snprintf(buffer, sizeof(buffer), "init_r=%d", ID);
return buffer;
}
void Test::process_data(char *payload)
{
const char delimiter[] = "=";
char parsedStrings[6][20];
char *token = strtok(payload, delimiter); // Points string after delimter
strncpy(parsedStrings[0], token, sizeof(parsedStrings[0])); // Copy the first one
for (int i = 1; i < 7; i++)
{
token = strtok(NULL, delimiter);
strncpy(parsedStrings[i], token, sizeof(parsedStrings[i]));
}
this->a = atoi(parsedStrings[2]);
this->b = atoi(parsedStrings[3]);
}
Now I'm aware that for example request_msg() should use a buffer defined in the header, since it will now return rubbish since it's only defined in there. And once the I call it in my code now already other data could be written in those allocations. About the process_data() function I'm completely clueless how to get this working. I want to parse incoming data like: identifier=text=20=5=5.0 and then it should parse it into char arrays of:
- text
- 20
- 5
- 5.0
which I later convert to float/int etc. This all works just fine in a .ino code I wrote, but here I'm clueless..
Any help or tips on to write this would be appreciated!