Hi, I intended to measure the voltage difference between two analogread signals (represented by anaval1 and anaval2), then compute the square of voltage and install them in the accumulated "sum" , 'Num" is to count the array index. The total length of the array is 78, when the "Num==78" the sum and Num should be 0 and start the array again. But from the serial monitor the Num keeps increasing until 90. The values from 78 to 90 all seem wrong and I don't know is it because the overflow? I wonder how to dispose the mainloop from NUM 78-90 and correct the results.
Here is my code:
long int anaval1[]={89,337,681,341,514,636,623,535,455,530,494,452,387,354,513,291,705,338,434,389,452,455,390,363,597,378,341,279,86,742,173,511,378,378,456,370,548,448,749,121,227,564,600,631,455,466,590,498,423,608,268,513,598,980,385,876,599,385,424,449,551,227,583,511,624,527,381,635,561,216,452,706,477,592,536,461,444,477};
long int anaval2[]={343,537,468,289,728,252,328,497,634,574,155,463,449,393,592,353,859,534,291,414,427,616,568,552,376,188,529,472,412,501,542,820,473,498,635,443,225,452,196,329,539,297,581,524,861,397,655,455,494,471,547,400,688,264,440,445,450,320,283,571,489,545,345,579,543,848,728,866,899,323,461,503,456,430,545,528,530,655};
unsigned long starttime;
unsigned long interval2 = 6000; //20s
unsigned long interval1 = 3000; //20s
long int sum;
int Num = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println(sizeof(anaval1)/sizeof(anaval1[0]));
//pinMode(analogPin1, INPUT);
//pinMode(analogPin2, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
if ((millis() - starttime < interval2) && (millis() - starttime > interval1)) {
long int volt=anaval1[Num]-anaval2[Num]; //double volt = map(analogRead(analogPin1) - analogRead(analogPin2),0,1024,0,4.8);
// int volt=analogRead(analogPin1) - analogRead(analogPin2);// if I use int here volt*volt is incorrect
// but if I use long here volt*volt is incorrect
// no matter I use long or int
delay(10);
Serial.print(Num);
Serial.print("\t");
Serial.print(anaval1[Num]);
Serial.print("\t");
Serial.print(anaval2[Num]);
Serial.print("\t");
Serial.print(volt);
Serial.print("\t");
Serial.print(volt*volt);
Serial.print("\t");
Serial.print(sum);
Serial.print("\t");
Serial.println();
sum = sum + volt*volt;
Num++;
} else if (Num>=sizeof(anaval1)/sizeof(anaval1[0])) {
sum = 0;
Num = 0;
starttime = millis();
}
}
And this is the serial monitor data
