OLED 128x64, Adafruit lib, Aduino Uno, very strange behavior on program size

It is really very strange.
Starting from a situation where the display works well, if I add in the
loop() section some extra instrucions (serial commands handling), the
OLED initalization phase (well behind, in the setup() section) fails sending
on the serial port the message:

SSD1306 allocation failed


If I add just before the end of loop() section:

if (Serial.available()) {
ch = Serial.read();
// if(ch=='h') printMenu();
// else if(ch=='2') writeEnableMask();
// else if(ch=='3') readEnableMask();
// else if(ch=='4') resetTrigger();
// else if(ch=='6') setEEPROM_tempoSecondi();
// else if(ch=='7') setEEPROM_numEventi();
// else if(ch=='8') setEEPROM_updateInterval();
// else if(ch=='r') { wdt_enable(WDTO_30MS); while(1); };

the program continues to work.

If I uncomment
if(ch=='h') printMenu();

the OLED init fails at boot
---> "SSD1306 allocation failed"

here in the setup() section

if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever


Someone already faced that?

Someone who can try my program?


All strings to be printed must be forced in FLASH

.print("string") ---> .print(F("string"))

This happened to other peoples but it is not normal that a compiler
is not able to count how much RAM locations are used to alert
the programmer.

Am I wrong?

Many libraries allocate SRAM usage at compile time e.g. 128x64 buffer

Nowadays, Adafruit_SSD1306 allocates the buffer at runtime.
This means it can use a smaller amount of SRAM for 128x32 than 128x64.

But punters just observe the "available memory" from the Build report and assume there is plenty.
Since a 128x64 buffer uses 1024 bytes of SRAM you should subtract 1024 from the "available" report.

Yes, putting fixed data in Flash is always a good idea. e.g. print(F("string"))

If you still don't have enough SRAM, change from Adafruit_SSD1306 to U8g2lib which can use a small "paged buffer"


Thaks David, now it is clear!