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 5
In this section we are going to start keeping track of how long the key is held down. We don't have to actually measure the time, instead we count how many times Arduino loops through our sketch while the key is down. As soon as we release the key we are going to print that value on the Serial Monitor. Also notice that we will put our counter back to zero when we do that.

We won't be printing X's across the screen any more, so delete the line highlighted in orange.

Then copy the 4 sections highlighted in yellow and and paste them into your sketch in the places shown.

Notice the new line in the sketch that says:

   downTime++; 
Another way to write the same line would be:
   downTime=downTime+1; 
They both add 1 to downTime everytime Arduino loops through this code.

Compile and Run the sketch.

The numbers that appear on your monitor indicate the number of times Arduino swings through the loop while you are holding down the key. The longer you hold down the key, the larger the number.

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 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);
   Serial.print ('X');
   downTime++;   //Count how long the key is down
   characterDone=false;
   delay(myBounce);
 }

 void keyIsUp() {
   noTone(speaker);
   if (!characterDone) {
      Serial.println(downTime);
      characterDone=true;
      downTime=0;
   }
}