Project 4.02 Generating a Specific Tone

In this project you will learn how to write a function that will generate a specific tone.

Project Code:

/////////////////////////////////////////
// 4.02 - Generating a Specific Tone

byte SW1 = 1;

bool pressed = LOW;

byte piezoPin = 12;

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

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

/*
  This function will generate a certain tone give a frequency in Hz.
*/
void BuzzPiezo(long frequency) {
  long period = 1000 / frequency;
  digitalWrite(piezoPin, HIGH);
  delay(period / 2);
  digitalWrite(piezoPin, LOW);
  delay(period / 2);
}
/////////////////////////////////////////  

*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.

The content of the loop() function is just like the last project except for this time the function takes a parameter (50). This parameter represents the frequency in Hz that we want the piezo to generate.

if (digitalRead(SW1) == pressed) {
  BuzzPiezo(50);
}

We are trying to create a certain tone, and to do that, we need to figure out something called a "period." But how do we find out what the period is from a frequency?

Well, a period is just the opposite (or reciprocal) of frequency. So, if we take 1 and divide it by the frequency, we get the period. However, since we're working with time in milliseconds, not seconds, we need to adjust our calculation. Instead of just 1 divided by the frequency, we use 1000 (because there are 1000 milliseconds in a second) divided by the frequency. That gives us our period in milliseconds!

long period = 1000 / frequency;

Remember that the period is the time for the piezo to turn on and off. This means that we have to delay by half the period after we turn it on and delay by half the period after we turn it off.

digitalWrite(piezoPin, HIGH);
delay(period / 2);
digitalWrite(piezoPin, LOW);
delay(period / 2);

We’ve now created a function to generate any frequency we want!

Previous
Previous

Project 4.03 Adding Duration

Next
Next

Project 4.01 Using Functions