The reason I think it is related is because when I add more thing to the buffer that will display the numbers of error I get in the screen matrix increases.
Example when displaying also some custom sprites (numbers from 0 to 7) and a text “Score:”:
It’s difficult to be sure. What board are you using and when you compile, how much of the SRAM is being used up? I’m wondering if your screen buffer is somehow too small for what you are trying to do and it’s walking all over the array storage?
for (int i = 0; i < SCREEN_HEIGHT; ++i) {
for (int j = 0; j < SCREEN_WIDTH; ++j) {
Serial.print(screen[i][j]);
Serial.print(" ");
}
Serial.println("");
}
Serial.println("");
And here how I display the values in the screen:
u8g2.clearBuffer();
for (int i = 0; i < SCREEN_HEIGHT; ++i) {
for (int j = 0; j < SCREEN_WIDTH; ++j)
drawSprite(spaceInvadersSprites, screen[i][j], j*SPRITE_WIDTH, i*SPRITE_HEIGHT, SPRITE_HEIGHT, SPRITE_WIDTH);
}
u8g2.drawStr(2, 6, "Score:");
char buff[32];
itoa(score, buff, strlen(buff));
u8g2.drawStr(34, 6, buff);
u8g2.sendBuffer();
Here is the drawSprite function too:
void drawSprite(const unsigned char *spriteSheet, int sprite, int x, int y, int h, int w) {
if (spriteSheet == NULL or sprite < 0) return;
if (h > 8) h = 8;
for (int i = 0; i < w; ++i) {
char c = spriteSheet[sprite*w+i];
for (int j = 0; j < h; ++j) {
if (c & 0x1) u8g2.drawPixel(x+i, y+j);
c = c >> 1;
}
}
}
Okey, I don’t know why, but when I change from an int matrix to a char matrix it just works perfectly. I would assume something had to see with the memory. If anyone know why let me know xd
Char takes up a single byte for each entry in the array. On an Arduino Uno, int take up two bytes.
The Uno only has a maximum on 2048 bytes of SRAM and you were using half of that for your buffer, from what you said above. The Arduino itself uses a few more, at least 9 bytes even in the Blink sketch, as it holds variables for the millis() counter and such like. Any libraries used in the sketch might use additional bytes too.
Also, if you use the String data type on an Uno, you are asking for trouble. It needs to do a lot of dynamic memory allocations “under the hood” and this can lead to SRAM fragmentation and “interesting” bugs to track down if the sketch runs out of SRAM during some of these hidden operations. The advice online, is to avoid these in Arduino sketches, or to use them at your own risk.
You check the output when you compile a sketch. It’s at the end:
...
Checking size .pio/build/uno/firmware.elf
Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
RAM: [= ] 13.0% (used 266 bytes from 2048 bytes)
Flash: [= ] 8.3% (used 2690 bytes from 32256 bytes)
Your SRAM is detailed on the first line where it says “RAM”. In the example given, I’ve used 266 bytes of SRAM out of a total of 2048 available.