I have been playing tonight with a monostable function.
The idea is to trigger a pulse output based on a 50-2000 Hz interupt driven input. my first simple try was to put the output high in the interupt service and use a delay to provide the pulse width back in the loop but I find the jitter on the pulse width is huge. Is that normal?
next try will be to use milli or micro to time the pulse width, is that a better way?
If it happens HERE, execution will go to the interrupt routine, set the pin high, return from then interrupt routine then the pin will immediately go LOW.
Hence, you will see a very very short high pulse on the pin, not even close to 10ms.
ah I think I see your point, the interupt returns to the same point in the loop, I was assuming it returned to the beginning, time for a rethink thanks
thanks for the replys guys and keeping me right mods, slowly getting the hang of it all. Here is the new code now working with a timer. Comments welcome
//--------------------------------------------------------------
//
// Interrupt driven sketch to output monostable pulse
// Input is on pin digital 2 ie external int0
// Output on pin 7
// test at 17Hz == 1000rpm == 60ms period
//
//--------------------------------------------------------------
unsigned long pulsewidth;
unsigned long zerotime;
unsigned long pulsetime;
volatile boolean flag;
// Interrupt Service Routine (ISR)
void isr ()
{
flag = true;
zerotime = millis();
digitalWrite(7, HIGH);
}
void setup()
{
pulsewidth = 20; //milliseconds
zerotime = 0;
flag = false;
attachInterrupt(0, isr, FALLING); //enable int0
pinMode(7, OUTPUT);
}
void loop(){
if (flag) {
pulsetime = millis() - zerotime;
if (pulsetime >= pulsewidth) {
digitalWrite(7, LOW); // turn off/LOW
flag = false;
zerotime = 0;
}
}
}
Thanks for the tip re using micros instead of mills I will change it.
The pulse duration was just for this test. Next step is to add a pure time delay which will be adjusted as a function of speed or frequency and the pulse duration will be determined by a fraction of the period. In case you had not guessed its basically a steam engine controller with variable valve timing and dwell angles. Currently im working on an rpm meter and the feed to a 4x7 segment display.