2.2 – SOS with Functions

Take a look at our code in 2.1 for causing an LED to blink SOS. There is a lot of repetition. What if we wanted to change the output pin from 13 to 8? How many lines of code would we have to go through to make that change? What if we wanted to change the timing of the dit or dah?

Functions allow us to to create named sections of code that perform a specific task. If we look at our SOS code we can certainly break it down into functions. We can create a function for blinking S, O, and even for the individual dits and dahs.

Let’s look at the letter S. In morse code the letter S is dit dit dit. In example 2.1 one dit is four lines of code and the letter S becomes 12 lines of code. We can break the code down into two functions. One to create a dit and one to create the letter S by calling the dit function three times. Here’s what this would look like:

//dit function
void dit(){
     digitalWrite(13,HIGH);
     delay(250);
     digitalWrite(13,LOW);
     delay(250);
}

//S Function
void S(){
     dit();
     dit();
     dit();
     //Add a delay for the spacing between letters
     delay(500);
}

Your Turn

Create a new sketch. In the new sketch add the function for dit and S from the code above and then create your own functions for dah and the letter O.

After you create the functions, in the loop function, create the morse code SOS using your new functions.

Don’t forget to add the pinMode line the setup function to set pin 13 as output:

void setup() {
    // put your setup code here, to run once:
    //pin 13 is the built in LED
    pinMode (13, OUTPUT);
}