I am looking for a formula / function or method for taking an incremental number that increases 1 per loop cycle, counting up from 1 to that number and adding said numbers.
example:
1 cycle = 1
2 cycles = 1+2
3 cycles = 1+2+3
4 cycles = 1+2+3+4
...and so on
Hope I am making sense I have no clue how to even wrap my head around this one. This sequence will only go on for a maximum of 100 cycles so it shouldn't have any issues as far as buffer / integer overflow.
int cycles = n, sum = 0;
for(int i = 1; i <= cycles; i++) sum += i;
I wonder if the compiler would pick that up? It's actually referred to (although I don't know if officially named) as the triangle sequence formula.
@OP
This is an AP (Arithmetic Progression Series); where, the differences of the adjacent terms are always the same. Simple algebra shows that the sum of all the terms of the AP series is:
S= n/2[2a+(n-1)d]
Where:
S = Summation of all the n terms
n = number of terms in the series
a = First term of the series
d = common difference
BTW: Give a try to write codes to compute the sum of: 2+6+10+14+18 (50)
bidouilleelec:
( n (n+1) )/ 2
This worked great! Exactly what I needed! Thank you all for figuring out what I couldn't.
For those wh have stumbled upon this thread and are looking for a snippet of code that functions here is the snippet I used the successfully test this:
int vreadcount = 0;
long vdropminus = 0;
long nextBattMillis = 0;
void setup() {
Serial.begin (9600);
}
void loop() {
if ((long)(millis() - nextBattMillis) >= 0) {
//update Battery status
nextBattMillis += 1000;
vreadcount = nextBattMillis /1000;
// put your main code here, to run repeatedly:
vdropminus = (vreadcount *(vreadcount+1) )/ 2;
Serial.print (vdropminus);
Serial.print ("/");
}
}
This code will be used to account for a strange drop in the analog signal using a voltage divider circuit to measure voltage on an analog pin. The code waits 1000ms (1 second) until it updates the voltage reading. (the analog pin reading is not present in this code) on the second reading, the value will drop roughly 17.4 and each reading that number will decrease by 0.34. (pulled from multiple test runs of the existing code and confirmed with a sanity check while measuring the batteries with a multimeter.) I'll post the full code when I figure it all out and confirm everything is running the way it should.