I have been working on a class that returns values stored in a progmem ARRAY. The function that prints the value within the class works, however, when I try to extract a pointer to the array item from the main sketch and then try to access the content directly I get garbage. Why?
Below is a minimal case example with 3 small files, with the same structure as my actual project.
Main sketch:
#include "test.h"
fruitSalad fruitlist;
void setup(){
Serial.begin(115200);
delay(500);
size_t cnt = fruitlist.showFruit(2);
Serial.println();
Serial.print("Bytes: ");
Serial.println(cnt);
Serial.println();
char * fruit = NULL;
cnt = fruitlist.getFruit(fruit);
if (cnt) {
char c;
for (size_t i=0; i<cnt; i++){
c = pgm_read_byte_near(fruit + i);
Serial.write(c);
}
Serial.println();
}
}
void loop(){
}
test.h:
#ifndef TEST_H
#define TEST_H
#include "Arduino.h"
#define FRUIT1 "Orange"
#define FRUIT2 "Lemon"
#define FRUIT3 "Cherry"
const char orange [] PROGMEM = {FRUIT1};
const char lemon [] PROGMEM = {FRUIT2};
const char cherry [] PROGMEM = {FRUIT3};
const char * const fruits[] PROGMEM = {
orange,
lemon,
cherry
};
class fruitSalad {
public:
fruitSalad();
size_t showFruit(size_t idx);
size_t getFruit(char * fruit);
private:
char * _fruitPtr;
size_t _fruitSize;
};
#endif // TEST_H
test.cpp:
#include "test.h"
fruitSalad::fruitSalad(){
_fruitPtr = NULL;
_fruitSize = 0;
}
size_t fruitSalad::showFruit(size_t idx){
char c;
_fruitPtr = (char *)pgm_read_ptr(fruits + idx);
_fruitSize = strlen_P(_fruitPtr);
for (size_t i=0; i<_fruitSize; i++){
c = pgm_read_byte_near(_fruitPtr + i);
Serial.write(c);
}
return _fruitSize;
}
size_t fruitSalad::getFruit(char * fruit){
fruit = _fruitPtr;
return _fruitSize;
}