I have written the following code to measure the speed of a unidirectional DC Motor.I have attempted to measure the time between successive interrupts in order to calculate speed.
boolean check;
boolean start;
unsigned int angle = 5; //angle moved per encoder tick
unsigned long volatile time1;
unsigned long volatile time_11;
unsigned long interrupt_time;
void setup() {
Serial.begin(9600);
while (!Serial) ;
pinMode(21, INPUT); //Pin#21=interrupt pin, matched to interrupt#2
attachInterrupt(digitalPinToInterrupt(2), speed, FALLING);
time1 = 0;
time_11 = 0;
interrupt_time = 0;
check = true;
start = false;
time_11 = millis(); //Start Clock
}
void loop() {
if(time1 == interrupt_time && start) //Both times same , hence bool start.
{
if(check)
{
Serial.print(millis()); //Time taken to rise to steady speed.
check = false;
}
Serial.println((angle/time1)*1000); //Display Speed.
}
interrupt_time = time1;
start = false;
while(!start)
{}
}
void speed(void) {
start = true;
time1 = millis()-time_11;
time_11 = millis();
}
I want the code to be as efficient as possible.I have around 100 ticks per 360 degrees from my encoder.Is there any chance of "missing" an interrupt?
time1
in theloop
the ISR might be called and the value oftime1
would change. The if statement might have compared the first two bytes of the long, but then checks the last two bytes of the new value. I hope this makes sense.Serial.println((angle/time1)*1000);
Be careful to not divide by 0. Also be aware that this is integer division and thus it will truncate (before multiplying by 1000).