Reducing PROGMEM and RAM Usage

From Arduboy Wiki
Revision as of 23:00, 9 July 2024 by Sublinear (talk | contribs) (Added page for Reducing PROGMEM and RAM Usage.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Overview

The Arduboy only has 28KiB or 29KiB (FX) of PROGMEM and 2.5KiB of RAM. While making a game, these can run out very quickly. This page aims to help you recover some of your precious PROGMEM and RAM.

Tips for Reducing PROGMEM

  • Look through your code in Ardens for large functions that shouldn't be there. Here is a step-by-step example: (Note: this will only work with .elf files, .hex files don't provide enough information.)
    • Launch Ardens and drag your .elf file on it.
    • Open the disassembly tab (Windows>Debugger>Disassembly)
      Opening the disassembly tab.
    • Click on the "Jump to Function" dropdown.
      The example contents of the Jump to Function dropdown. Note the amount of floating-point functions present.
    • Scan the dropdown for anything unexpected.
    • In our example, there are a huge amount of float functions that are taking up a lot of space.
    • How can we fix this? In our source code, we can change x from a float to a uint8_t:

#include <Arduboy2.h> Arduboy2 arduboy; -- float x; ++ uint8_t x; void setup() {     arduboy.begin();     arduboy.setFrameRate(10); } void loop() {     if (!arduboy.nextFrame())         return;     arduboy.clear();     x++;     arduboy.print(x / 10);     arduboy.display(); }

Tips for Reducing RAM

  • Put PROGMEM on arrays/data that will not change. Note you will have to use pgm_read_byte(&array[index]) or some variant of it (see documentation here).
  • Declare variables constexpr if they do not change.
  • Put string literals in PROGMEM by surrounding them with the F("string literal here") macro. Pharap's FlashStringHelper library is very helpful when dealing with strings in PROGMEM.
  • Use locals instead of globals when possible. Locals are stored on the stack and exist only in a scope, while globals are stored for the entire lifetime of the program.
  • Pack variables into bits as much as possible. For example, instead of using an array of 8 bools, use 1 byte with each bit representing a bool. Reading and writing bits can be done with bitRead(number, bit) and bitWrite(number, bit, value).