2

I am running this piece of code in my loop() function on Arduino Uno:

int times = 400;
int i;
double raw[times];
for (i = 0; i < times; i++) {
    Serial.println(i);
    raw[i] = (double) i;
}

for (i = 0; i < times; i++) {
    Serial.println(raw[i]);
}

When times is less than 500, it prints fine, but when times approaches 500, the serial print would stop at random places or print weird characters and sometimes would not print at all.

Is it something to do with the RAM usage?

Passer By
  • 19,325
  • 6
  • 49
  • 96
TPWang
  • 1,322
  • 4
  • 20
  • 39

3 Answers3

4

The Arduino Uno uses the ATmega328P microcontroller. If you look at the first page of the datasheet for that microcontroller: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf you'll notice it says:

2KBytes Internal SRAM

Your array is located in SRAM. The size of the array in bytes can be calculated by: sizeof(double) * times. In this case sizeof(double) is 4 bytes so when you set times to 500 the array uses 2000 bytes. Some additional SRAM is required for the rest of the code running on your Uno so you are using more memory that is available. This results in undefined behavior, thus the undesirable results you are experiencing.

per1234
  • 878
  • 5
  • 13
2

An easy way to check this is to hardcode the array: enter image description here

As you can see, the sketch uses 1,798 bytes of RAM, and the compiler is already complaining. If you change this to 500, it will tell you that you're using more RAM than you already have.

dda
  • 6,030
  • 2
  • 25
  • 34
  • It will as you need some ram for the stack & heap as well. So you cant actually use 100% of your RAM for global variables. – 0___________ Apr 29 '17 at 08:40
1
  1. As @per1234 mentioned RAM is one issue
  2. double are extremely expensive for this small micro. Every calculation takes hundreds of clock cycles, printing needs a lots of RAM & uC time. You should try to use integers / long integers instead - using scaling algorithms
0___________
  • 60,014
  • 4
  • 34
  • 74