Project 4.03 Adding Duration
Building on the last project, in this project we will be adding duration to our function. This means that we can play different tones for different amounts of time.
Project Code:
///////////////////////////////////////// // 4.03 - Adding Duration byte SW1 = 1; bool pressed = LOW; byte piezoPin = 12; void setup() { pinMode(piezoPin, OUTPUT); pinMode(SW1, INPUT); } void loop() { if (digitalRead(SW1) == pressed) { // Hz ms BuzzPiezo(5, 1000); BuzzPiezo(50, 1000); BuzzPiezo(500, 1000); } } /* This function will generate a certain tone for a certain time given a frequency in Hz and a duration in ms. */ void BuzzPiezo(long frequency, long duration) { long period = 1000 / frequency; long cycles = duration / period; for (long i = 0; i < cycles; i++) { 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.
This time, the BuzzPiezo function is called with two parameters: the first one is the frequency and the second one is the duration of the tone in milliseconds.
void loop() { if (digitalRead(SW1) == pressed) { // Hz ms BuzzPiezo(5, 1000); BuzzPiezo(50, 1000); BuzzPiezo(500, 1000); } }
Like before in the function, we have to know the period to generate the frequency. As a reminder, period is 1 / frequency but in our case is 1000 / frequency since we are working in milliseconds. Unlike last time we need the tone to happen for a certain amount of time. This means we have to know how many periods make up the desired time.
For example, If the frequency passed is 50Hz, and the time passed is 1000:
1000ms / 50Hz = 20ms (<- Period)
So how many 20ms cycles are there in 1000ms?
1000ms / 20ms = 50 cycles (<- How many times the period should happen)
So, we know that the period is 20ms and that period needs to happen 50 times. This sounds like the perfect opportunity for a for-loop!
for (long i = 0; i < cycles; i++) { digitalWrite(piezoPin, HIGH); delay(period / 2); digitalWrite(piezoPin, LOW); delay(period / 2); }
We are basically saying play a 50Hz tone 50 times.