Using PROGMEM for byte arrays in a library

Hello everyone,

I am using PROGMEM in a very simple library created by me and I encountered with inconsistent results.
So far I have been using PROGMEM out of libraries and never had this problem. I get different results whether I use the library to print an array of bytes or if I print it from a PROGMEM variable created in the main sketch.

--> Here there is the Header file of the library:

#ifndef provaLibrary_h
#define provaLibrary_h
#include "Arduino.h"
#include <avr/pgmspace.h>

class provaLibrary{
public:
provaLibrary(int a);
int _a;
void impr();
const byte myByteArray[8] PROGMEM={0xCC,0x12,0xFF,0x02,0x01,0x7E,0x7E,0x7E};
};

#endif

--> and the cpp file of the library:

#include "Arduino.h"
#include "provaLibrary.h"
#include <avr/pgmspace.h>
provaLibrary::provaLibrary(int a){
_a=a;
}

void provaLibrary::impr(){
byte myByte;
for (int k = 0; k < 8; k++){
myByte = pgm_read_byte(myByteArray + k);
Serial.print(myByte,HEX);
Serial.print(" ");
}
Serial.println();
}

--> and the .ino file where I use the library:

#include "provaLibrary.h"

provaLibrary myLibraryObject(10);
const byte myByteArray[8] PROGMEM={0xCC,0x12,0xFF,0x02,0x01,0x7E,0x7E,0x7E};

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);

}

void loop() {

myLibraryObject.impr();
delay(3000);

byte myByte;
for (int k = 0; k < 8; k++){
myByte = pgm_read_byte(myByteArray + k);
Serial.print(myByte,HEX);
Serial.print(" ");
}
Serial.println();

}

Note that I use exactly the same code to print myByteArray[8] (in the library and in the main .ino file), and I get different results when printing:

3A 2 30 91 36 2 23 E0 //Different bytes printed for the same "7E" byte!!???
CC 12 FF 2 1 7E 7E 7E

Can anyone help me??

Thank you very much!

Please read the two posts at the top of this Forum by Nick Gammon on the proper way to post source code here using code tags. It will help us help you.

class provaLibrary{
  public:
    provaLibrary(int a);
    int _a;
    void impr();
    const byte myByteArray[8] PROGMEM={0xCC,0x12,0xFF,0x02,0x01,0x7E,0x7E,0x7E};
};

You can't have PROGMEM as a non-static class variable.

You can make your class like this:

class provaLibrary{
  public:
    provaLibrary(int a);
    int _a;
    void impr();
    static const byte myByteArray[8] PROGMEM;
};

And define the variable in your .cpp file:

const byte provaLibrary::myByteArray[8] PROGMEM={0xCC,0x12,0xFF,0x02,0x01,0x7E,0x7E,0x7E};

That works.

Why are you defining myByteArray[] in two different places?

Who, me?

@Nick: No, we posted just minutes apart. He doesn't use the static modifier in his definition.

I think he's just proving a point, that it works in one place and not in another.

Thank you so much Nick! That works!

Sorry for the way I posted the code, it was my first one. I'll do it the proper way next time.
And yes, I was just trying to show that it worked with PROGREM outside the library but not inside.