In my debouncing stuff that i've done I had to increase the time from 50ms to around 200ms.
I also had to not use the time parameter passed in to the event handler, but instead use DateTime.UtcNow as well as wrapping the event handler in a lock block. Here's a quick example (untested) to replace the entire button_OnInterrupt check.
private static bool _currentState = false; private static void button_OnInterrupt(uint port, uint data, DateTime time) { lock(this) { var now = DateTime.UtcNow; if (LastInterrupt.AddMilliseconds(200) > now) { LastInterrupt = now; return; } _currentState = !currentState; //I don't trust data because of bouncing onboardLED.Write(_currentState); reqnum++; HttpWebRequest.Create("http://192.168.1.80/this?" + reqnum + "=" + _currentState).GetResponse().Dispose(); LastInterrupt = now; //set this here because it's possible the web request takes longer than 200ms which would break the debounce. Calls to the handler are queued up. You might want to consider moving the state changes into a queue and have a seperate thread process the queue, though that's more complicated. } }FYI, UtcNow is faster than .Now
THANK YOU!! Your input was key! Here's the final routine, seems rock solid now.
private static void button_OnInterrupt(uint port, uint data, DateTime time)
{
lock (D1)
{
var now = DateTime.UtcNow;
Boolean newValue = false;
newValue = D1.Read();
if (LastInterrupt.AddMilliseconds(100) > now && lastvalue == newValue)
return;
// Activate the LED when button is pressed (data == 1)
lastvalue = newValue;
onboardLED.Write(lastvalue);
reqnum += 1;
String s = newValue.ToString();
String t = String.Concat("http://192.168.1.80/this?D1=");
//if (data == lastvalue)
// return;
HttpWebRequest test = (HttpWebRequest)HttpWebRequest.Create(String.Concat(t, s));
//try
//{
test.GetResponse();
test.Dispose();
//}
//catch (Exception ex)
//{
// Debug.Print(ex.Message);
//}
LastInterrupt = now;
}
}