Project 4.01 Using Functions

At this point in our programming journey, we need to be using functions in our programs. Functions make programming much easier to read and write. They make doing the same thing repeatedly much easier. This program is actually the exact same as the last but put into a function.

Project Code:

/////////////////////////////////////////
// 4.01 - Using functions

byte piezoPin = 12;

byte SW1 = 1;
bool pressed = LOW;


void setup() {
  pinMode(piezoPin, OUTPUT);
  pinMode(SW1, INPUT);
}

void loop() {
  if (digitalRead(SW1) == pressed) {
    BuzzPiezo();
  }
}

/*
  It is good practice to put a function description here.
  Example:
  This function applies alternating voltage to the Piezo speaker
    at an period of 2ms.
*/
void BuzzPiezo() {
  digitalWrite(piezoPin, HIGH);
  delay(1);
  digitalWrite(piezoPin, LOW);
  delay(1);
}
/////////////////////////////////////////

*If you’re copying and pasting the code, or typing from scratch, delete everything out of a new Arduino sketch and paste / type in the above text.

This time in the loop instead of a bunch of code you’ll only see a few lines. This line calls the function BuzzPiezo. Inside of this function is the code from the loop() function from the last program. The program just calls this function over and over again in the loop() if the SW1 is pressed.

void loop() {
  if (digitalRead(SW1) == pressed) {
    BuzzPiezo();
  }
}

When making a function it is good practice to put a function description right above it in a comment. This will remind you or tell someone else what the function does. Using the “/* */” format here will allow you to easily write a multi-line comment.

/*
  It is good practice to put a function description here.
  Example:
  This function applies alternating voltage to the Piezo speaker
    at an period of 2ms. 
*/

Remember a function has a few parts. The return type, function name, parameters if it takes any, and the code inside of the brackets. See the table below for a breakdown of the BuzzPiezo function:

Part Name Part
Return Type Void (It does not return anything)
Function Name BuzzPiezo
Parameters None in this case
Code inside brackets
digitalWrite(piezoPin, HIGH);
delay(1);
digitalWrite(piezoPin, LOW);
delay(1);
                
void BuzzPiezo() {
  digitalWrite(piezoPin, HIGH);
  delay(1);
  digitalWrite(piezoPin, LOW);
  delay(1);
}
Previous
Previous

Project 4.02 Generating a Specific Tone

Next
Next

Project 4.00 Using the Piezo