I would like my button to do 2 of the following things;
The current code that I'm working with looks a little like this:
//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();
//}
}
}
But how can I check whether the button is held for 2 or 3 seconds?
I found a way to fix my problem by using a Stopwatch that measures the time that the button is being pressed.
Above our namespace we need to add this in order for us to use the Stopwatch class.
using System.Diagnostics;
Now we want to declare a Stopwatch by:
Stopwatch stopWatch;
When the button is pressed and held my code will pick that up with the FallingEdge
. When it is pressed I also want it to create a new Stopwatch and start it.
When the button is released, which is checked by RisingEdge
. I stop the timer and get the time between the 2 events. I then compare the time pressed in an if statement so I can decide what to do with the buttonpress. In this case SendWord, or Append current char and preview it.
//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();
}
}
}
If there is any better way to tackle my problem, please let me know but so far this solution works for me.
I needed this as I was working on a Raspberry Pi project with Morse code input via buttons. That input then had to be displayed on a LCD screen. If the user was satisfied with his input he could then send it to the other user(s) by holding the Right button for 2 seconds.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.