Nibbles and Bits
The Care and Feeding of My Pet Arduino
by Budd Churchward - WB7FHC - NIBBLES AND BITS LIBRARY
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:
This is where Arduino chases his tail.
val=digitalRead(myKey);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.