1

I want to feed thousands of analog vibration sensor readings into an array as fast as possible, and then analyze them. Here is my sketch:

const int pSensor1 = A0;
const int aSize=10000;

int a[aSize];

void setup() 
{
  pinMode(pSensor1, INPUT);
  Serial.begin(9600);
}

void loop() 
{
  for (int i = 0; i < aSize; i++) a[i] = analogRead(pSensor1);

  int RMS = 0;
  for (int i = 0; i < aSize; i++) RMS += pow(a[i], 2);
  RMS = sqrt(RMS/aSize);

  Serial.println("Hello");
}

This compiles and runs fine. My problem arises when I try to change the last line to:

Serial.println(RMS);

I get the error:

Arduino: 1.8.12 (Windows 10), Board: "Arduino Nano, ATmega328P"

Sketch uses 3270 bytes (10%) of program storage space. Maximum is 30720 bytes. Global variables use 20188 bytes (985%) of dynamic memory, leaving -18140 bytes for local variables. Maximum is 2048 bytes. data section exceeds available space in board Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint. Error compiling for board Arduino Nano.

Why does attempting to Serial print a single floating point variable use 985% of dynamic memory?

3

Probably if you don't print them then the compiler sees that array is never used for anything so it gets optimized away. It sees that it is useless code that doesn't affect anything and simply removes it. Once you print it then it actually has to be included in the compiled code.

Think about this. The Arduino you are using has 2000 bytes of memory. One int takes 2 bytes. You want 10,000 of them. That's 20,000 bytes of memory. 20,000 bytes will never ever fit into 2,000 bytes. You need to choose a more reasonable number of samples.

| improve this answer | |
  • That makes sense, thank you. – Benjamin Jordan Apr 28 at 2:03
  • 3
    Re “You need to choose a more reasonable number of samples”: 10,000 is a perfectly reasonable number of samples for an Arduino Nano. However, storing the samples before computing the RMS value is not reasonable. – Edgar Bonet Apr 28 at 8:13
  • OK, maybe I should have said that differently. – Delta_G Apr 28 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.