Main Site Documentation

Puzzler: It works! (most of the time)


#1

I was working on a project and was foiled by a simple pushbutton! It was unreliable despite the glitch filter. It turned out to be a coding error on my part. I’ve re-created it in a simple program below. Can you spot the mistake? If you think this is obvious, please let novice users take a stab. I don’t have any prizes, just your own satisfaction that you’re smarter than me. :slight_smile:

using System;
using System.Threading;
using GHIElectronics.NETMF.FEZ;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;

namespace DebounceTest
{
    public class Program
    {
        static OutputPort led;
        static long counter = 0;

        public static void Main()
        {
            SetupPorts();
            Debug.Print("Ready for test. Press the button!");
            Thread.Sleep(Timeout.Infinite);
        }

        private static void SetupPorts()
        {
            led = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.LED, false);

            Microsoft.SPOT.Hardware.Cpu.GlitchFilterTime = new TimeSpan(0, 0, 0, 0, milliseconds: 200);
            InterruptPort startButton = new InterruptPort((Cpu.Pin)FEZ_Pin.Digital.Di12, true, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeLow);
            startButton.OnInterrupt += new NativeEventHandler(startButton_OnInterrupt);
        }

        static void startButton_OnInterrupt(uint data1, uint data2, DateTime time)
        {
            led.Write(true);
            Thread.Sleep(50);
            led.Write(false);

            counter++;
            Debug.Print("You have pressed the button " + counter.ToString() + " times.");
        }
    }
}


#2

Looks to me like your startButton is going to get garbage collected.

-Eric


#3

[quote]Looks to me like your startButton is going to get garbage collected.

-Eric[/quote]
:clap: Good job EricM. :clap:

It took me longer than I’d like to admit to realize my error. It takes quite a few button presses before GC hits, so I didn’t think there was anything wrong with my app. It would merrily work for a while and just went bonkers as if I hit the button randomly.

Moving the startButton as a static global variable fixed it.


#4

I have been a full time C# programmer for the last 3 or 4 years. Been there my friend … That is what is great about this forum we all have different strengths and help each other.

-Eric