Nibbles and Bits
The Care and Feeding of My Pet Arduino


Morse Code Oscillator

« 1 2 3  4  5 6 »

Section 4 - Writing the Sketch
Copy and paste the sketch on the right into your project. When you run it you should hear tones when you press the telegraph key.

Here is how it works:

We start by declaring variables for our INPUT and OUTPUT pins. Notice that we have are setting myKey to equal 14. There is no pin 14 labeled on the Arduino. We will be using analog pin A0. When you declare your analog pins to be digital you must use the numbers: 14, 15, 16, 17, 18 and 19.
      int myKey=14;   
      int speaker=11; 
val will be where we store the state of the key. If it is down it will equal 1. If it up it will be 0. myTone is the frequency of the note you will hear. You can try different values.
      int val=0;      
      int myTone=440; 

Declare our INPUT and OUTPUT pins:
      void setup() 

This is where Arduino chases his tail.

      void loop() 
While he is spinning around, we have him check our key:
If the key is down, we play the tone:
        if (val) tone(speaker,myTone); 
If the key is up, we turn the tone off. !val means 'NOT val'. It is just a shorter way of testing for zero.
        if (!val) noTone(speaker); 

Give this a try and see how it goes. In the next section we will show you a short video of the sketch in operation using our homemade clothespin telegraph key. In the final section we will give you a complete listing of International Morse Code that you can print and use for study and practice.

Next Section »

/* Barnacle Budd's Sending Morse Code Part 1 demo v. 0.1
   Morse Code Oscillator
   (c) 2011, Budd Churchward - WB7FHC
   This simple little sketch will check for key up or down
   It will play a tone while the key is down and shut it off
   when the key is up. This is just a basic starting point
   for more projects with Morse Code.

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

void setup() {
  pinMode(myKey, INPUT);

void loop() {
  val=digitalRead(myKey);          // Read the state of the key
  if (val) tone(speaker,myTone);   // If it is down play the tone
  if (!val) noTone(speaker);       // If it is not down stop the tone