Main Site Documentation

Using interrupts to measure the duty cycle of a PWM signal


#1

I have a 600Hz PWM signal coming from a sensor. I’d like to read it’s duty cycle in my code. The code I’ve written looks like this:

	public class PwmIn : IDisposable
	{
		InputPort _in;
		DateTime _lastRise = DateTime.Now;

		public long Period { get; private set; }
		public long PulseWidth { get; private set; }
		public double DutyCycle { get { return (double) PulseWidth / Period; } }

		public PwmIn(FEZ_Pin.Interrupt pin)
		{
			_in = new InterruptPort((Cpu.Pin)pin, true,
				Port.ResistorMode.PullDown,
				Port.InterruptMode.InterruptEdgeBoth);

			_in.OnInterrupt += new NativeEventHandler(sensorInterrupt);
		}

		void sensorInterrupt(uint port, uint state, DateTime time)
		{
			const long ticksPerMicrosecond = TimeSpan.TicksPerMillisecond / 1000;

			long timeSpan = (time - _lastRise).Ticks / ticksPerMicrosecond;

			if(state == 1) //Rising Edge
			{
				Period = timeSpan;
				_lastRise = time;
			}
			else if (state == 0) //Falling Edge
			{
				PulseWidth = timeSpan;
			}
		}

		public void Dispose()
		{
			_in.Dispose();
		}
	}

However, I’m concerned that the interrupts have too great a latency for this to work. I’ve heard this can take 20ms.

I’m planning to run this on a FEZ Panda II, with a set of 16 of these sensors.

Can I expect to get reasonable accuracy in my duty-cycle readings? Or do I need to get a dedicated bit of hardware to read these?


#2

Why not use this PinCapture?


#3

I didn’t know it existed. I’ll take a look at it. Thanks!