Go Down

Topic: knowing the order of two pulses (Read 99 times) previous topic - next topic

Dahom_s

hello everyone.
i'm new here and hopefully i would learn from you.
if i have two pulses coming from two sensors , i want to know the order which pulse was high first ?
or maybe i can average the value of two pulses over 5 seconds maybe and see what value is the highest ?
the project is a tachometer that can tell direction of revolution with 999 RPM max.
the code so far :



{{{{{{{{{{{{

#include<LiquidCrystal.h>
LiquidCrystal lcd(12,11,6,5,4,3);
float value=0;
float rev=0;
int rpm;
unsigned long t1=0;
int time;



void isr() //interrupt service routine
{
rev++;
}

void setup()
{
lcd.begin(16,2);                //initialize LCD
attachInterrupt(digitalPinToInterrupt(2),isr,FALLING);//attaching the interrupt

}

void loop()
{
delay(1000);
detachInterrupt(0);           //detaches the interrupt
time=millis()-t1;        //finds the time
rpm=(rev/time)*60000][;         //calculates rpm
t1=millis();             //saves the current time
rev=0;


 if (rpm>999){
  lcd.clear();
lcd.setCursor(0,0);
lcd.print("Error");

}

else
{

lcd.clear();
lcd.setCursor(0,0);
lcd.print("TACHOMETER ");
lcd.setCursor(0,1);
lcd.print(     rpm);
lcd.print(" RPM");
lcd.print(" CW ");

}
attachInterrupt(digitalPinToInterrupt(2),isr,FALLING);
}


}}}}}}}}}}}}}}}



thank you all

PS: how does exactly ISR and interrupt (attaching and detaching) work here ?
i looked it  up but there was no clear answer.

thank you again.

jremington

#1
Feb 29, 2020, 07:14 pm Last Edit: Feb 29, 2020, 07:24 pm by jremington
Please edit your post to add code tags, as described in "How to use this forum" and correct the code. It won't compile due to errors like this: "][".

There is no point in attaching and detaching interrupts in the loop function. 

"rev" should be made unsigned int and MUST be declared volatile, for it to be shared with an interrupt, e.g.
Code: [Select]
volatile unsigned int rev=0;

When using a variable shared with an interrupt routine, make a protected copy, like this, and use that copy for subsequent calculations. Otherwise it will be corrupted.
Code: [Select]

cli();  //disable interrupts
rev_copy = rev;
sei(); //re-enable

MarkT

I strongly advise never using detachInterrupt() unless you understand the ramifications (basically there's no need to).

To read a quadrature encoder (which I think is what you have, not a tachometer - which is an analog device)
perhaps an encoder library is a place to start?
[ I will NOT respond to personal messages, I WILL delete them, use the forum please ]

Go Up