I have a project where I want to track the time (millis) between the last instance and an instance that happened X instances back.
I want to display the average of the said instance (detected with a proximity switch) over the last X times it's happened.
I want to be able to change that X to a value that the user will choose. Maybe 10, maybe 30... maybe even 50 or larger if feasible.
The first way I thought of doing this was a dynamically allocated array. Then I read that I shouldn't do that. So then I thought, I'd set the max size for it. But then I don't know if that makes the most sense.
So is this really my only two options or am I missing another trick?
Oh, and I also would like to keep the average to the last X times. So I would be constantly needing the milli that happened X times back, not just once but each time future time it happened as well.
Safest is to use a fixed array size of the maximum that you will allow the user to set.
If the user only has to enter the setting once (in setup), dynamic allocation is fine as long as you limit the amount of allocated memory to something sensible and understand what can go wrong (and hence put preventative measures in place so it does not go wrong).
If you will allow the user to change it on the fly, you're getting into dangerous territory when using dynamic allocation.
Now the question is if you need to store all measurements; I might not understand your requirement completely. Maybe you can sum the values, keep track of how many values you have sum'ed and calculate the average.
Gilligan:
The first way I thought of doing this was a dynamically allocated array. Then I read that I shouldn't do that. So then I thought, I'd set the max size for it. But then I don't know if that makes the most sense.
You are better off allocating a static array from the start.
Deciding how big that can possibly be will be difficult enough, leaving space for enough stack and some heap.
Having a large pool of memory which is dynamically allocated and de-allocated by multiple tasks makes sense when the running average usage will be less than if all the tasks kept big static chunks to themselves. That really doesn't apply to an Arduino.
Dynamic allocation does not gain you anything here.
Check out: Available Memory for how to measure memory while running, but remember stack is dynamic and some classes will use dynamic allocation internally (like the dreaded Serial.print()). Squeezing the last ounce of memory is a right pain... you would be better off buying a processor with more memory.
Yours,
TonyWilk
Please check these classes (especially the examples)
and maybe