I had exact same problem and james's answer helped me realize the problem is related to heap memory.
In addition to what he has already commended, I found here that you should also wrap all your constant strings in F() function.
For example instead of
display.println(" Madgayrah");
You write
display.println(F(" Madgayrah"));
This will store the string in the flash memory instead of SRAM.
Another thing I found is that callingAlso if you only use OLED display.display() twice without for printing anything could cause it to hang.text, I strongly recommend the more lightweight SSD1306Ascii library
For example:
display.println(F("welcome\n"))
display.display();
if (temperature > 60) {
display.println(F("welcome\n"));
}
display.display();
In that case if temperature <= 60, you end up calling display.display() second time without having anything newIt output text to oled display. I found that without buffering which causes slight flickering but massively reduce the amount of memory required to be problematic at least with my displaydrive the OLED.
Another helpful tip is to use arduino's watchdog. Basically after you enable that you need to constantly call wdt_reset(); function and if you failed to call it for certain amount of seconds, arduino will automatically reset.