I'm looking for help in my Morse Code Translator project. The main problem I have is counting how long a button is pressed for. Thanks in advance for any helpful responses.
‘When’ the switch is closed, record the current value of millis().
‘When’ the switch opens, subtract the time recorded above from the current value of millis().
This value tells you the number of milliseconds the switch was pushed, the rest should be easy.
Details....
Arduino millis() function returns the time count as an unsigned long.
It will count up to 4 billion and some milliseconds then roll over to 0 and start counting up. That takes 49.7-some days.
Because of using unsigned long, subtracting start time from end time always works even across the rollover.
With signed integers there would have to be a check and one way different from the other which is slower +and+ the longest interval you could time will be half as long as with unsigned integers.
When you special rollover code in a program it was written by someone who doesn't know so they wrote what they could.
=============================================================
You could check the pin as slowly as once a millisecond. A short pulse might be 200 to 400 HIGH detects in a row while a long pulse might be 600 to 800 -- best way to know is by feeding it pulses and see how many they take.
int highCount, prevHighCount;
....
// somewhere in loop()
if ( millis() - startWait >= 1000UL )
{
prevHighCount = highCount;
if ( digitalRead( pin ) == HIGH )
{
highCount++;
}
else
{
highCount = 0;
}
startWait += 1000UL; // set up next wait and check
}
// end of pin checker
Keep that bit simple. Write other code that uses prevHighCount to tell how long (count is ms HIGH) the pulse was,
if (( highCount == 0 ) && ( prevHighCount > 0 ))
{
// here is where you tell pulses apart
}
===============================================
You will also need to track how long the space between pulses to tell when one letter ends and the next begins, no?
So maybe the pin check needs to count LOW reads as well and have a prevLowCount.