Hello,

I'm writing a program for my Arduino MEGA2560, and I just can't seem to figure out a solution for my problem. I'm reading a series of data from incremental encoders, and calculating movement data from the received values. I calculate the velocity, which just works fine by dividing the distance of two subsequent positions with the time passed from the beginning of the loop to the end. I would like to calculate average velocity as well by summing the calculated velocities (Vel_Sum) and dividing the result with the number of the data (datacounter). For some reason I cannot add the measured velocity to the summed value, it always stays 0.00. I've tried several methods: -adding the momentary velocity to a variable called Vel_Sum in the loop, and then dividing Vel_Sum with a datacounter value -creating a function outside the loop which performs the summing and dividing -creating two functions outside the loop one performing the summing and the other the dividing

I also tried to debug, by printing out the variables. Oddly enough, once it worked even after I commented out the print, but stopped working when I deleted the commented out line. I used several prints, and I couldn't determine if there was any crucial line which I should have left in.

The relevant code snippets (the Diff_Cal function calculates the distance between the subsequent positions using the received data):

```
//Variables for velocity
float V0_A = 0.00;
float V1_A = 0.00;
unsigned long t0 = 0;
unsigned long t1 = 0;
unsigned long dt = 0;
//Max and average velocity
float VMax_A = 0.00;
int datacounter = 1;
float VSum_A = 0.00;
float VAvg_A = 0.00;
//Calculating Velocity
float Vel_Cal (float Delta, float dt) //This works
{
float V;
V = Delta/dt;
return V;
}
//Calculating Average Velocity
float Vel_Sum (float Vel_Sum, float Vel)
{
Vel_Sum = Vel_Sum + Vel;
return Vel_Sum;
}
float Avg_Vel (float Vel_Sum, float datacount)
{
float Avg_Vel;
Avg_Vel = Vel_Sum / datacount;
return Avg_Vel;
}
void loop()
{
//Setting V0 to the previous value
V0_A = V1_A;
V0_B = V1_B;
//Path
Delta_A = Diff_Cal(Coord_A[0], Coord_A[1], Coord_A[2], X_A_Coord_prev, Y_A_Coord_prev, Z_A_Coord_prev);
//Calculating velocity, acceleration and smoothness
//Setting t1---------------
t1 = millis();
//Calculating elapsed time between two samples in milliseconds
dt = abs(t1-t0);
//-------------------------
//Velocity
V1_A = Vel_Cal(Delta_A, dt);
//Average velocity
VSum_A = Vel_Sum(VSum_A, V1_A);
VAvg_A = Avg_Vel(VSum_A, datacounter);
//Max Velocity
if (V1_A > VMax_A) {VMax_A = V1_A;}
Serial.print("V1_A: ");
Serial.print(V1_A, 2);
Serial.print(", VSum_A: ");
Serial.print(VSum_A, 2);
Serial.print(", VAvg_A: ");
Serial.print(VAvg_A, 2);
Serial.print(", VMax_A: ");
Serial.print(VMax_A, 2);
Serial.print(", Acc1_A: ");
//Setting t1
t0 = millis();
datacounter = datacounter + 1;
}
```