SOS Blink Solution
The following is the original SOS Code:
/*
NAME
SOS
Engineering Period 1
DATE
Revision History
DATE | NAME | Changes Made
------|------------|------------------------------
TODAY | My Name | Initial Implementation
*/
void setup() {
// put your setup code here, to run once:
//pin 13 is the built in LED
pinMode (13, OUTPUT);
}
void loop() {
//Send an S
//DIT Start
digitalWrite(13,HIGH);
delay(250);
digitalWrite(13, LOW);
delay(250);
//DIT END
//DIT Start
digitalWrite(13,HIGH);
delay(250);
digitalWrite(13, LOW);
delay(250);
//DIT END
//DIT Start
digitalWrite(13,HIGH);
delay(250);
digitalWrite(13, LOW);
delay(250);
//DIT END
//End of the S lets Pause to separate our letters
delay(500);
//Send the Letter O
//DAH Start
digitalWrite(13,HIGH);
delay(750);
digitalWrite(13, LOW);
delay(250);
//DAH END
//DAH Start
digitalWrite(13,HIGH);
delay(750);
digitalWrite(13, LOW);
delay(250);
//DAH END
//DAH Start
digitalWrite(13,HIGH);
delay(750);
digitalWrite(13, LOW);
delay(250);
//DAH END
//End of the O - Another pause to separate letters
delay(500);
//Send the S Again...
//DIT Start
digitalWrite(13,HIGH);
delay(250);
digitalWrite(13, LOW);
delay(250);
//DIT END
//DIT Start
digitalWrite(13,HIGH);
delay(250);
digitalWrite(13, LOW);
delay(250);
//DIT END
//DIT Start
digitalWrite(13,HIGH);
delay(250);
digitalWrite(13, LOW);
delay(250);
//DIT END
//End of the message pause before repeating the message or next word
//Note this pause is a little longer than between letters.
delay(1250);
}
And now SOS using functions:
/*
NAME
SOS - Using Functions
Engineering Period 1
DATE
Revision History
DATE | NAME | Changes Made
------|------------|------------------------------
TODAY | My Name | Initial Implementation
*/
void setup() {
// put your setup code here, to run once:
pinMode(13,OUTPUT);
}
//dit function - Dot
void dit(){
digitalWrite(13,HIGH);
delay(250);
digitalWrite(13,LOW);
delay(250);
}
//dah function - Dash
void dah(){
digitalWrite(13,HIGH);
delay(750);
digitalWrite(13, LOW);
delay(250);
}
//S Function
void S(){
dit();
dit();
dit();
//Add a delay for the spacing between letters
delay(500);
}
//O Function
void O(){
dah();
dah();
dah();
//Add a delay for the spacing between letters
delay(500);
}
void loop() {
S();
O();
S();
//End of the message pause before repeating the message or next word
//Note this pause is a little longer than between letters.
delay(1250);
}
If you count the actual lines of code in our two versions of SOS you will see the first iteration, the one without functions, has 40 lines of executable code. The revised version of code, using functions, has 21 lines of code.
Supposing your requirements changed and you were asked to use pin 8 rather than 13. It will be a lot quicker to update the code that uses functions and less error-prone.
When writing your own projects, be sure to look for areas where functions will help reduce code redundancy.