Nibbles and Bits
The Care and Feeding of My Pet Arduino


by Budd Churchward - WB7FHC - NIBBLES AND BITS LIBRARY


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 6
Now let's have some fun. In this section, we will wait for the key to come back up. When it does, we will look at how long it was down and print either a dit or a dah on the monitor window.

We will need to declare two more variables:

      boolean ditOrDah=true; 
      int dit=100;           
You may have to adjust the value of dit to make it match your sending speed. Later we will have our sketch do the adjusting automatically.

We are also adding a proceedure called printResults(). For now we will use it to display values so that you can see how they change while you are sending code. Later this proceedure will have a different purpose and we will change its name.

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

Delete the line highlighted in orange.

Compile and run the program. You should see your dits and dahs on the Serial Monitor.

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;

void setup() {
  pinMode(myKey, INPUT);
  pinMode(speaker,OUTPUT);
  // initialize the serial communication:
  Serial.begin(9600);
}



 void loop() {
   val=digitalRead(myKey);
   if (val) keyIsDown();
   if (!val) keyIsUp();
 }
 
 void keyIsDown() {
   tone(speaker,myTone);
   downTime++;   //Count how long the key is down
   characterDone=false;
   ditOrDah=false;
   delay(myBounce);
 }

 void keyIsUp() {
   noTone(speaker);
   if (!ditOrDah) {
       printResults();
   }
   if (!characterDone) {
      Serial.println(downTime);
      characterDone=true;
      downTime=0;
   }
}
void printResults() {
  ditOrDah=true;
  if (downTime<dit) {
    // We got a dit
    Serial.print ('.');
  }
  else {
    // We got a dah
    Serial.print ('-');
  }
}