I'm trying to make a speedometer, with utilization of interrupt for get number of pulse and some calculation for getting speed, but when compute speed the arduino freeze for some second and i lose alot of impulse and false all my successive capture of impulse. Why? thanks for reply
const int contaImpulsi = 2;
volatile int impulsi = 0;
int impulsiOld = 0;
static int appoggio = 0;
unsigned deltaT[3];
unsigned vel = 0;
void setup() {
Serial.begin(9600);
attachInterrupt(contaImpulsi, definisciTempi, RISING);
}
void loop() {
if (impulsiOld == impulsi || impulsi > impulsiOld)
{
if (appoggio == 3) {
deltaT[3] = millis();
appoggio = 0;
}
if (appoggio == 2) {
//Serial.println("ASSEGNO DELTA T 2");
deltaT[2] = millis();
//Serial.println(deltaT[2]);
appoggio = 3;
}
if (appoggio == 1) {
//Serial.println("ASSEGNO DELTA T 1");
deltaT[1] = millis();
appoggio = 2;
}
if (appoggio == 0) {
//Serial.println("ASSEGNO DELTA T 0");
deltaT[0] = millis();
appoggio = 1;
}
}
impulsiOld = impulsi;
if (appoggio == 3) {
int t1 = (deltaT[1] - deltaT[0]);
int t2 = (deltaT[2] - deltaT[1]);
int dividi = t1 + t2;
vel = (((690 * 2000 / dividi) * 3.6) / 10) * 0.85; // here i think is where the program freeze
Serial.println("------------------------------------------");
Serial.print("SPEED: ");
Serial.println(vel);
Serial.println("------------------------------------------");
}
}
void definisciTempi() {
impulsi++;
}
deltaT
has 3 elements, but you are writing to 4 and only reading from 3.appoggio
is 3,appoggio
gets set to 0 and the if block forappoggio == 0
gets also executed in the same loop.