Main Site Documentation

Interrupts and pulse-length


#1

Guys,

what would be the most effective way of counting pulses with a specified min/max pulse-length in an interrupt routine?

I came up with this, but there’s probably a more elegant way:


		static int min = 80; //minimum pulse length
		static int max = 100; //maximum pulse length

		static void OnInterrupt(uint pin, uint state, DateTime time)
		{
			long pulsestart = 0;
			long pulsestop = 0;

			if (state == 0)
			{
				pulsestart = time.Millisecond;
			}
			if (state == 1)
			{
				pulsestop = time.Millisecond;
			}
			if ((pulsestop - pulsestart) > min & (pulsestop - pulsestart) < max)
			{
				if (state == 0) //halleffect switch goes low when activated
				{ 
					//increase counter
				}
			}
}


#2

static int min = 80 *10000; //minimum pulse length in ticks
static int max = 100 * 10000; //maximum pulse length in ticks

long lastTick=0;
long cnt=0;
long tickLength;
 
static void OnInterrupt(uint pin, uint state, DateTime time)
{
 
	if (state == 0)
	{
		lastTick=time.Ticks;
	}
	if (state == 1)
	{
		tickLength= time.Ticks - lastTick;
		if (tickLength>min && tickLength<max) {cnt++;}
	}
}