Project 4.01 Bringing the Piezo to Life
A sound is created using a piezo element by rapidly switching its voltage source on and off. The rate at which we switch the piezo creates a particular tone. Upload this sketch and listen to the tone it creates.
Concepts: delayMicroseconds
Circuits:
Concepts: delayMicroseconds
Circuits:
The frequency of a tone is expressed in hertz (Hz), which is the number of vibrations per second. We use three variables: the frequency in hertz (freq), the number of microseconds between vibrations (period), and the number of microseconds in a second (aSecond):
long freq;
long period;
long aSecond = 1000000;
At the beginning of the loop() block we set the frequency:
freq = 4000;
Next, we need to calculate how many microseconds that need to pass between each vibration. The math is simple:
period = aSecond/freq;
Now we’re ready to enter the loop() block. We’re going to create the vibrations one by one. Since freq is vibrations/second, we can use it to determine how long the tone lasts. We create a tone of 1/10th of a second by looping from 0 to freq/10:
for(long k = 0; k < freq/10; k++){
At this point the code is simple: we switch the piezo on and off. Since we want a cycle to be completed every period, we switch it on for period/2 and then off for period/2. The delay command would really limit the range of frequencies we could create. Using delayMicroseconds allows us to control the frequency to the nearest 2 microseconds (two one-millionth of a second!):
digitalWrite(piezo,HIGH);
delayMicroseconds(period/2);
digitalWrite(piezo,LOW);
delayMicroseconds(period/2);
Finally, we delay a second between tones before starting all over again:
delay(1000);
long freq;
long period;
long aSecond = 1000000;
At the beginning of the loop() block we set the frequency:
freq = 4000;
Next, we need to calculate how many microseconds that need to pass between each vibration. The math is simple:
period = aSecond/freq;
Now we’re ready to enter the loop() block. We’re going to create the vibrations one by one. Since freq is vibrations/second, we can use it to determine how long the tone lasts. We create a tone of 1/10th of a second by looping from 0 to freq/10:
for(long k = 0; k < freq/10; k++){
At this point the code is simple: we switch the piezo on and off. Since we want a cycle to be completed every period, we switch it on for period/2 and then off for period/2. The delay command would really limit the range of frequencies we could create. Using delayMicroseconds allows us to control the frequency to the nearest 2 microseconds (two one-millionth of a second!):
digitalWrite(piezo,HIGH);
delayMicroseconds(period/2);
digitalWrite(piezo,LOW);
delayMicroseconds(period/2);
Finally, we delay a second between tones before starting all over again:
delay(1000);