I have the following code in loop() to collect values from an electret microphone
for(int i=0; i<sampleSize; i++){
analogVal[i]= analogRead(ADC_Pin);
sumOfSquares= sumOfSquares+sq(analogVal[i]);
}
Serial.print("Sum of squares: ");
Serial.print(sumOfSquares);
where sampleSize is an int variable, I've tried numbers from 3 to 1000, which is my desired value. ADC_Pin is an int variable set to be A1 and has been properly initialized through pinMode. analogVal is an int array of size sampleSize.
My circuit appears to be fine because the output produces a reasonable amount of voltage. I've tried eliminating the line with sumOfSquares and just having the first line in the for loop. However, the Serial Monitor hangs and does not display any values. The serial communication is at 9600 bps.
1 Answer 1
Arduino UNO have 2K RAM (many other too). That is 2048 bytes of RAM.
I suppose, that analogVals[]
is declared as int
and having 1000 entries it takes 2000 bytes of RAM, leaving wholesome 48 bytes
for all your others variables (including int i
in the for cycle and Serial
outside it) and stack for calling functions (like analogRead
and sq
) and all theirs variables and functions and arguments.
So int i
= 2B, Serial
= 2B, sumOfSquares
= 2B, "Sum of squares: "
= 17B of what I see takes anothe 23 bytes
of those 48 bytes
leaving us with only 25 bytes for all else.
I bet, that you try to use more REAM, than you have and so your stack overflows
and
destroys some variable content on the vay
is overwriten by assigning to some variables, which then leads to all sort of problems.
Serial.begin(115200);
[or whatever the data rate is that you have your serial monitor set at] ¶ Anyway, I don't know what the problem is, and if you don't edit your question to include a Minimal, Complete, and Verifiable example of code -- with visible definitions of every variable used, etc -- perhaps nobody else will be able to tell either.analogVal
? What issumOfSquares
? What is thesq()
function? In short: DO NOT POST SNIPPETS LIKE THIS - POST A COMPLETE PROGRAM SO WE CAN SEE THE ENTIRE PROGRAM AND VARIABLE DECLARATIONS.