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 14 15 16 17 18 19 »

Section 2
The first thing we are going to do is split out the two lines that turn the tone on and off. We will take them out of loop() and put them into their own procedures.

Start by deleting the lines highlighted in orange on the right.

Then copy the ones highlighted in yellow and paste them into your sketch as you see here.

Compile your sketch and run it. It should behave exactly as it did before.

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

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

 void loop() {
   if (val) keyIsDown();
   if (!val) keyIsUp();
void keyIsDown() {

void keyIsUp() {