Hi everyone,
I got some code that is working fantastic. But i found it on the forums and i don't really understand it completely. After running once a second for about twenty minutes my N+2 runs out of memory though. I think it gets to big a queue up of interrupts built up. That's what i guess from this thread.
I really need to poll this sensor at, at least 1 Hz but preferably 2 or 4. But it runs out of memory. Can someone suggest changes to the code to allow for this. Like I said earlier, It is otherwise perfect.
Here is the class.
using System;using System.Threading;using Microsoft.SPOT;using Microsoft.SPOT.Hardware;using SecretLabs.NETMF.Hardware;using SecretLabs.NETMF.Hardware.Netduino;namespace Pulsator{ public class Sonic { public static int uDistance; private static int ticks; private static InterruptPort EchoPin = new InterruptPort(Pins.GPIO_PIN_D2, true, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth); private static OutputPort TriggerPin = new OutputPort(Pins.GPIO_PIN_D1, false); public static int Read() { EchoPin.OnInterrupt += new NativeEventHandler(port_OnInterrupt); EchoPin.DisableInterrupt(); Distance(); //Debug.Print("distance = " + myDistance + " mm."); Thread.Sleep(25); return uDistance; } public static void Distance() { EchoPin.EnableInterrupt(); TriggerPin.Write(false); Thread.Sleep(2); TriggerPin.Write(true); Thread.Sleep(10); TriggerPin.Write(false); Thread.Sleep(2); } private static void port_OnInterrupt(uint port, uint state, DateTime time) { if (state == 0) // falling edge, end of pulse { int pulseWidth = (int)time.Ticks - ticks; // valid for 20°C //int pulseWidthMilliSeconds = pulseWidth * 10 / 582; //valid for 24°C int pulseWidthMilliSeconds = (pulseWidth * 1 / (int)578.29); //change 1 to 10 for mm //Debug.Print("Distance = " + pulseWidthMilliSeconds.ToString() + " millimètres."); uDistance = pulseWidthMilliSeconds; } else { ticks = (int)time.Ticks; } EchoPin.ClearInterrupt(); } }}
Here is how I call it.
while (true) { lcd.Move(2, 0); lcd.Show(Sonic.Read().ToString() + "cm "); Thread.Sleep(1000); }
Thanks in advance.