Hello everybody,
I'm quite new with Arduino and programming with C-like code. So probably I made some mistakes in assigning of variables formats.
Following the complete code. I know that is performing 3 times the same calculation, but during the test of the distance sensor I noticed that something was wrong, so I decided to print out as much as possible and see where the problem arises.
So I started with declaring all variables unsigned long. And then after seeing that the results had no sense I decided to declare variables as float.
unsigned long CurrDist;
unsigned long PrevDist;
unsigned long CurrentTime;
unsigned long PrevTime;
unsigned long Vobst;
float calc;
void setup() {
Serial.begin(9600);
Serial.println("Ready");
delay(5000);
PrevDist=800;
PrevTime=millis();
}
void loop(){
int in=analogRead(A0);
if (in<=81) {CurrDist=800;}
else if (in<=122){CurrDist=800-0.7317*(in-81)*10;}
else if (in<=143){CurrDist=500-0.4762*(in-122)*10;}
else if (in<=184){CurrDist=400-0.2439*(in-143)*10;}
else if (in<=225){CurrDist=300-0.1220*(in-184)*10;}
else if (in<=266){CurrDist=250-0.1220*(in-225)*10;}
else if (in<=327){CurrDist=200-0.0820*(in-266)*10;}
else if (in<=471){CurrDist=150-0.0347*(in-327)*10;}
else if (in<=563){CurrDist=100-0.0217*(in-471)*10;}
else if (in<=604){CurrDist=80-0.0244*(in-563)*10;}
else if (in<=645){CurrDist=70-0.0244*(in-604)*10;}
else {CurrDist=55;}
CurrentTime=millis();
float Vobst= long(PrevDist-CurrDist)/(long(CurrentTime-PrevTime))*1000;
Serial.print ("ingresso= ");
Serial.println(analogRead(A0));
//Serial.println(pow(analogRead(A0),(-1,26)));
Serial.print ("Distanza= ");
Serial.print (CurrDist);
Serial.print("[mm] \t Velocità=");
Serial.print(Vobst);
Serial.println("[mm/s]");
Serial.print("current time=");
Serial.print(CurrentTime);
Serial.print("[ms] previous time=");
Serial.print(PrevTime);
Serial.println("[ms]");
Serial.print(long(PrevDist-CurrDist));Serial.print("/");Serial.print(CurrentTime-PrevTime);
calc=(float(PrevDist-CurrDist))/long((CurrentTime-PrevTime));
Serial.print("=");Serial.println(calc);
Serial.print("0-1="); Serial.println(0-1);
Serial.println("");
PrevDist=CurrDist;
PrevTime=CurrentTime;
delay(5000);
}
The thing that seem very strange to me is that even for small negatives values the problem occurs:
-8/5071=846966.56
Thanks in advance