Nibbles and Bits
The Care and Feeding of My Pet Arduino


Teaching Arduino to Copy Morse Code

« 1 2 3 4 5 6  7  8 9 10 11 12 13 15 16 17 18 19 »

Section 7
It may be nice to see our dits and dahs streaming across the monitor, but we will not be able to decode any letters if we don't pay attention to the length of silent time. When sending Morse Code, there is a short gap of silence between each letter and a longer gap between each word. We have done a good job of measuring the key down time. Now we need to keep track of how long we have waited between the dits and dahs.

To do this we need to declare two new variables:

      long FullWait=10000;    
      long WaitWait=FullWait; 
WaitWait is a counter that will start out with a high value and then count down to zero. When we declare it, we give it the value we have already stored in FullWait. Each time we let it count all the way down, we will put it back to FullWait again. Later when we want Arduino to automatically adjust to the sender's speed, we can give FullWait a new value. For now, all we need to do is print a space on the monitor when WaitWait gets to zero. If the sender hits the key before the counter runs out, we bounce it back up and start counting down all over again.

As before, copy and paste all the sections highlighted in yellow.

The line highlighted in orange should be deleted. Use caution here, an identical line was just added in the if struction pasted above it. Make sure you delete the one that is outside of that structure.

Hopefully, now you see why we wanted the boolean variable: characterDone. Without it, Arduino would keep printing a long string of spaces while the key was silent. We count down to zero, reset our counter and print one space. Then we don't count down again until the next time the key is pressed.

Compile and run the program. You should see your dits and dahs on the Serial Monitor with spaces between the letters.

Next Section »

int myKey=14;    // We are borrowing Analog Pin 0 and using it as digital
int speaker=11;  // Speaker will be hooked between pin 11 and ground

int val=0;       // A value for key up and down
int myTone=440;  // Freq. of our tone

boolean ditOrDah=true;
int dit=100;

boolean characterDone=true;
int myBounce=2;
int downTime=0;

long FullWait=10000;
long WaitWait=FullWait;

void setup() {
  pinMode(myKey, INPUT);
  // initialize the serial communication:

 void loop() {
   if (val) keyIsDown();
   if (!val) keyIsUp();
 void keyIsDown() {
   downTime++;   //Count how long the key is down

 void keyIsUp() {
   if (!ditOrDah) {
  if (!characterDone) {
      WaitWait--;  //We are counting down
      if (WaitWait==0) {
        Serial.print(' ');

void printResults() {
  if (downTime<dit) {
    // We got a dit
    Serial.print ('.');
  else {
    // We got a dah
    Serial.print ('-');