繁体   English   中英

具有Raspberry Pi GPIO的保持/按下按钮

[英]Hold/Push Button with Raspberry Pi GPIO

我希望我的按钮可以执行以下两项操作;

  • 只要按下按钮就做某事
  • 按住按钮一定时间(2秒)时,请执行某些操作

我正在使用的当前代码看起来像这样:

    //Comfirming a letter or sending the word.
    private void btnRightValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
    {
        //if button is pressed it will confirm a letter
        if (e.Edge == GpioPinEdge.FallingEdge)
        {
            //code to confirm letter
            ConfirmLetter();

            //if(buttonHeldForAWhile)
            //{
            //Send message
            //SendWord();
            //}
        }
    }

但是,如何检查按钮是否保持2或3秒钟?

我找到了一种使用秒表来解决问题的方法,该秒表可以测量按钮被按下的时间。

在我们的命名空间上方,我们需要添加它以便我们使用Stopwatch类。

using System.Diagnostics;

现在,我们要通过以下方式声明秒表:

Stopwatch stopWatch;

按住按钮时,我的代码将通过FallingEdge拾取。 当它被按下时,我也希望它创建一个新的秒表并启动它。

释放按钮时,由RisingEdge进行检查。 我停止计时器并获取两个事件之间的时间。 然后,我将比较if语句中的按下时间,以便我可以决定如何处理按钮按下。 在这种情况下,SendWord或追加当前字符并预览。

    //Comfirming the chosen letter.
    private void btnRightValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
    {
        if (e.Edge == GpioPinEdge.FallingEdge)
        {
            stopWatch = new Stopwatch();
            stopWatch.Start();
        }

        if (e.Edge == GpioPinEdge.RisingEdge)
        {
            stopWatch.Stop();
            long duration = stopWatch.ElapsedMilliseconds;

            if (duration > 2000 )
            {
                SendWord();
            }
            else
            {
                //Add the current character to the word
                _currentWordSB.Append(Convert.ToString(_currentChar));

            //    //Reset currentChar aswell
                _currentChar = ' ';

            //    //The user confirmed the morse sequence and wants to start a new one, so we reset it.
                _morseCode.Clear();

            //    //Preview the word
                PreviewLetter();
            }
        }
    }

如果有更好的方法来解决我的问题,请告诉我,但到目前为止,该解决方案对我而言仍然有效。

我在通过Raspberry Pi项目进行莫尔斯电码通过按钮输入时需要这个。 然后必须将该输入显示在LCD屏幕上。 如果用户对其输入感到满意,那么他可以通过按住“向右”按钮2秒钟将其发送给其他用户。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM