I am trying to write my own Arduino library and I would like to make it useful not just for ESP32/ESP8266 boards but also with Arduino boards.
I have created my header file like this
test.cpp
#ifndef TEST
#define TEST
#include "Arduino.h"
#define MAX_STRING_LEN 50
class MyClass{
private:
public:
String getString();
char * getCharPointer();
char * getAnotherCharPointer();
};
#endif
and my
test.cpp
#include "test.h"
static char buffer[MAX_STRING_LEN+1];
String MyClass::getString(){
// Sample REST API call
String testString = String("{\"test:\" \"hello String json\"}");
return testString;
}
char * MyClass::getCharPointer(){
// Sample REST API call
const char * sample_json = "{\"test:\" \"hello Char Pointer json\"}";
strcpy(buffer, sample_json);
return buffer;
}
char * MyClass::getAnotherCharPointer(){
// Sample REST API call
const char * sample_json = "{\"test:\" \"hello Another Char Pointer json\"}";
strcpy(buffer, sample_json);
return buffer;
}
My test file main.cpp
main.cpp
#include <Arduino.h>
#include "test.h"
MyClass myClass;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println(myClass.getString());
Serial.println(myClass.getCharPointer());
Serial.println(myClass.getAnotherCharPointer());
}
void loop() {
// put your main code here, to run repeatedly:
}
Result is ok
{"test:" "hello String json"}
{"test:" "hello Char Pointer json"}
{"test:" "hello Another Char Pointer json"}
I have these doubts that I would like to ask for suggestions.
- Is returning the String class in Header files, not a good idea? For ESP32/ESP8266 they are okay as they have big memory but for Arduino Uno boards I see a lot of discussions about not using String because it is bad and causes memory fragmentation etc.
- Is returning char * the safest way to make it compatible and useful to all MCU boards?
- Next question in char pointer, I often see this pattern done when returning char pointers like in this Time.cpp wherein a static buffer is used and defined at the implementation file (test.cpp) and all functions(getCharPointer, getAnotherCharPointer) that needs to return a char pointer just manipulates the static char buffer by using strcpy. Is this the proper way to go in Arduino programming?
Can somebody please clear my doubts? Thank you.